Re: help for back_inserter and end()
"Jess" <wdfcj@hotmail.com> wrote in message
news:1174821036.892785.48010@p15g2000hsd.googlegroups.com...
The iterator adaptor "back_inserter" takes a container and returns a
iterator so that we can insert elements to the end of the container.
Out of curiosity, I tried to look at what element the returned
iterator refers to. Here is my code:
#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;
int main(){
vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
cout << (*(back_inserter(v)));
return 0;
}
The code above couldn't compile. Since "back_inserter" returns an
iterator, then I would think I can dereference it. What's wrong with
it?
A back_inserter is an output iterator -- you can't read with it,
only write.
I also tried to copy containers using "copy", and instead of
"back_inserter", I used "end()". The code is:
#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;
int main(){
vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
vector<int> w;
v.push_back(3);
v.push_back(4);
copy(w.begin(),w.end(),v.end()); //instead of back_inserter, I
used .end()
for(vector<int>::const_iterator i = v.begin(); i != v.end(); i++)
cout << (*i) << endl;
return 0;
}
I was told the code above was wrong, but surprisingly, it compiled and
worked.
It "worked" only in the sense that the nasty thing you did happened
not to bite -- you overwrote the end of the vector. Depending on
the capacity of the vector, or whatever follows it in memory, the
copy may or may not cause apparent damage. But the vector doesn't
get any bigger, as your display loop should have revealed.
I'm really puzzled by what "back_inserter" does and when I
can replace back_inserter by copy.
Well, back_inserter cooperates with the underlying container in
growing it as needed, while copy doesn't.
HTH,
P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com