What is the right way of using c++ stl iterators instead of traditional pointers?
c++, stl
Solution
The difference between
const vector<double>::iterator
and
vector<double>::const_iterator
is roughly the same as between `double * const v` and `const double *v`:
- the first says that the iterator must remain constant, but what it points to can be changed
- the second says that the iterator itself is changeable, but what it points to is `const`.
If you rewrite the function as
void f(const vector<double>::iterator first, const vector<double>::iterator last) {
for(vector<double>::iterator it = first; it != last; it++)
*it = 10;
}
it would compile and run correctly.
Problem
I have the following very basic question. I want to use stl iterators instead of traditional C-type pointers for filling an array in a function. By the C-style way I mean the following example: ``` void f(double* v, size_t n) { for (int i = 0; i < n; i++) v[i] = 10; /* a more reasonable value in practice! */ } ``` I would convert this to the C++ style using the iterators as follows: ``` void f(vector<double>::const_iterator first, vector<double>::const_iterator last) { for(vector<double>::iterator it = first; it != last; it++) *it = 10; } ``` But I get compilation errors. If I use `iterator` instead of `const_iterator` the problem will be solved. However, I was wondering if that is the correct way? Because I thought `vector.begin()` and `vector.end()` iterators are constant. Thanks in advance!