I'm doing some homework, which includes a generic class with a lot of methods and constructors, but I'm only interested in the following constructor where i take the elements from initializer list and put them in my Container:
template <typename T, template <typename...> class Container = std::vector>
class Tok{
Container<T> collection;
public:
Tok(std::initializer_list<T> list);
}
We were told we cant use push_back function from algorithm, but only insert elements using insert function from algorithm. Firstly I implemented the constructor like this:
template <typename T, template <typename...> class Container>
Tok<T,Container>::Tok(std::initializer_list<T> list){
auto it2=collection.end();
for(auto it1=list.begin(); it1!=list.end(); it1++) {
{collection.insert(it2,*it1); it2++;}
}
}
But it didn't work, the program was crashing and throwing a memory error. Then I changed it a bit and got it to work using the next implementation:
template <typename T, template <typename...> class Container>
Tok<T,Container>::Tok(std::initializer_list<T> list){
for(auto it=list.begin(); it!=list.end(); it++)
collection.insert(collection.end(),*it);
}
Now my question is why doesn't the first one work, and what is the difference between these two?(I get the same result using begin instead of end)