J
john smith
Hi, I'm a little confused as to why the following code generates and error
when compiling:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void f(vector<int>::const_iterator& b, vector<int>::const_iterator& e)
// compiler complains about this line
{
copy(b, e, ostream_iterator<int>(cout, " "));
}
int main()
{
vector<int> v1;
back_insert_iterator<vector<int> > bii(v1);
*bii++ = 10;
*bii++ = -2;
*bii++ = 5;
f(v1.begin(), v1.end()); // compiler complains about this.
return 0;
}
But I change the function definition to const vector<int>::const_iterator,
the program compiles and runs fine. Also, the copy statement also works. I
had always thought that if you put a const keyword before a type, then that
means you are not going to change that type, and I thought that
const_iterators mean that the contents of the container cannot be changed.
So, the combination of const and const_iterator means I have an iterator
that can't be changed, that points to a container that the contents cannot
be changed. However, the copy line works, but copy increments the iterator
b. So, now I'm confused about the use of const and iterators. Thanks in
advance for your help.
Smith
when compiling:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
void f(vector<int>::const_iterator& b, vector<int>::const_iterator& e)
// compiler complains about this line
{
copy(b, e, ostream_iterator<int>(cout, " "));
}
int main()
{
vector<int> v1;
back_insert_iterator<vector<int> > bii(v1);
*bii++ = 10;
*bii++ = -2;
*bii++ = 5;
f(v1.begin(), v1.end()); // compiler complains about this.
return 0;
}
But I change the function definition to const vector<int>::const_iterator,
the program compiles and runs fine. Also, the copy statement also works. I
had always thought that if you put a const keyword before a type, then that
means you are not going to change that type, and I thought that
const_iterators mean that the contents of the container cannot be changed.
So, the combination of const and const_iterator means I have an iterator
that can't be changed, that points to a container that the contents cannot
be changed. However, the copy line works, but copy increments the iterator
b. So, now I'm confused about the use of const and iterators. Thanks in
advance for your help.
Smith