i present you my problem
I’ve 2 list, named them A and B.
list<vector<int> > A = {{1},{2},{3}};
list<vector<int> > B = {{4},{5},{6}};
What i want is to have A = {{1,4},{1,5},{1,6},{2,4},{2,5},{2,6},{3,4},{3,5},{3,6}} without use any tmp list.
I use C++11 with gcc 4.6.3 on Ubuntu 12.04
So that the minimize code:
auto A_begin = A.begin();
auto A_end = A.end();
auto B_begin = B.begin();
auto B_end = B.end();
for(auto i = A_begin; i != A_end; ++i) //loop on A
{
for (auto j = B_begin;j != B_end; ++j) //loop on B
{
vector<int> tmp = (*i); // A[i]
copy((*j).begin(),(*j).end(),back_inserter(tmp)); // append B[j] to A[i]
A.emplace_back(tmp); //add it to A
}
}
A.erase(A_begin,A_end); // remove {1},{2},{3}
So, i think the algo is ok, but it make a infinit loop on A.
That I think is that A_end change when i make a A.emplace_back, but i save it, so i realy don’t know wat append here.
my code to identify the problem:
auto A_begin = A.begin();
auto A_end = A.end();
auto B_begin = B.begin();
auto B_end = B.end();
int ii = A.size();
for(auto i = A_begin; i != A_end; ++i) //loop on A
{
for (auto j = B_begin;j != B_end; ++j) //loop on B
{
vector<int> tmp = (*i);
A.emplace_back(tmp);
}
cout<<--ii<<endl; // exit when print 0 ?
}
This print negative number, and I’ve to ^C again.
EDIT : I find a solution:
auto A_begin = A.begin();
auto A_end = A.end();
auto B_begin = B.begin();
auto B_end = B.end();
list<vector<int>> tmp_l;
for(auto i = A_begin; i != A_end; ++i) //loop on A
{
for (auto j = B_begin;j != B_end; ++j) //loop on B
{
vector<int> tmp = (*i); // A[i]
copy((*j).begin(),(*j).end(),back_inserter(tmp)); // append B[j] to A[i]
tmp_l.emplace_back(move(tmp)); //add it to A
}
}
swap(tmp_l,A);
These two lines:
will be invoking undefined behaviour. By copying to tmp.end() you are simply overwriting memory after the end of A[i], not extending A[i]. You need to use a back_insert iterator, something like:
You’ll also need to include the header to get the back_inserter.
EDIT: Also, the A_end iterator points to the position “past the end” of the list so no matter how many items you add to a they are always added in front of A_end, hence the infinite loop. I’m not sure if there’s a good way to deal with this. There’s no benefit here in not creating a temporary list, you are allocating the same memory either way, just write into a new list.