J
Jess
Hello,
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?
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. I'm really puzzled by what "back_inserter" does and when I
can replace back_inserter by copy.
Thanks a lot!
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?
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. I'm really puzzled by what "back_inserter" does and when I
can replace back_inserter by copy.
Thanks a lot!