I am working on a project in c++ (11) and am having some issues with returning a vector from a function. A minimal working example of my problem is as follows:
#include <iostream>
#include <vector>
using namespace std;
vector<int*> find_items()
{
vector<int*> items;
int a[2] = {1,2};
items.push_back(a);
cout << items.at(0)[0] << endl;
return items;
}
int main()
{
vector<int*> items = find_items();
cout << items.at(0)[0] << endl;
return 0;
}
I'd like to be able to work with vectors of arrays of size 2 for my project, so I am using a vector of pointers to the first elements of those arrays. This seems to work fine except when I need to return such a vector from a function.
In this code, from my naive perspective, I should be getting the same output at both cout's, but instead the second print appears to be a garbage number.
I've read that c++ returns a copy of a vector when a function returns one. But in that case, wouldn't new pointers to the same memory be created in the copy of the vector? My guess is that these new pointers are in fact pointing to the wrong place. Is this copy not deep enough, or something along those lines? What would be the correct way to return the vector in this situation?
Thanks very much for any help!