Here is some example code:
#include <iostream>
#include <vector>
template <typename T>
std::vector<typename T::iterator> f(T t)
{
std::vector<typename T::iterator> v;
for (auto i = t.begin(); i != t.end(); ++i)
{
v.push_back(i);
}
return v;
}
template <typename T>
void print(const std::vector<T>& v)
{
for (auto i = v.begin(); i != v.end(); ++i)
{
std::cout << **i << ' ';
}
std::cout << std::endl;
}
int main()
{
std::vector<int> v{1, 2, 3};
print(f(v));
std::vector<std::vector<int>::iterator> itervec = f(v);
print(itervec);
}
On ideone the output was:
1 2 3
163487776 2 3
Questions
If I change f(T t)
to f(T& t)
the output is as expected. I'm assuming because I am working with copies of containers, technically the iterators I am pushing back on the vector are not the same as the vector I created in main. Is this correct?
The one thing I noticed is print(f(v));
prints 1 2 3
as expected but as soon as I assign it to itervec
the first iterator becomes garbage, is this all implementation dependent?