Why is an adaptor neccesary?

Hi Guys !

I don't know why is it necessary to use an adaptor here in this case in order for the program to insert to the destination container...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>

using namespace std;

int main() {
	
	vector<int> ivec;
	list<int> ilst;
	
	for(vector<int>::size_type s = 1; s <= 10; ++s)
		ivec.push_back(s);
	//The following line of code Will Not insert anything to ilst
	//unique_copy(ivec.begin(), ivec.end(), ilst.begin());
	//Only the adaptor can do the inserting
	unique_copy(ivec.begin(), ivec.end(), back_inserter(ilst));
	
	for(list<int>::iterator i = ilst.begin(); i != ilst.end(); ++i)
		cout << *i << "\t";
	
	return 0;
}


Why can't I use ilst.begin() as an argument for unique_copy to insert elements ?
Why can only the adaptor (in this case back_inserter) get the job done?

Thanks in advance for the explanations.

Jose
It could be because if ilst is empty, then begin() == end() which is not a valid place to write to.
If we expand on firedraco's answer,there should be enough room in the destination container between the given start iterator and container.end() to fit in all the possible values or
you will get that error because the destination container won't automatically expand to fit.

EDITED: for clarity
Last edited on
Yes, basically because the container needs to be expanded so the new elements fit.
back_inserter() does nothing more than call push_back() on the element to insert it.
Thank you very much, firedraco's answer and the extended explanation by guestgulkan seem very correct and acceptable to me. it does make sense that in between iterators wouldn't be much room for insertion.
Thank you very much once more for all the support.

Jose.

PS. Keep up the good work !
Topic archived. No new replies allowed.