I’m having problems copying a multidimensional vector, I’ve tried many things but this is the last one:
vector < vector < int > > a;
vector < vector < int > > b;
a.resize(10);
b.resize(10);
a[0][0] = 123;
copy( a.begin(), a.end(), back_inserter(b) );
cout << b[0][0];
I’m trying to do a recursive loop that counts all possible routes in a grid within 10 moves. I’m trying to create a vector called current_path which would hold the current path for each recursion, when the current_path has 10 moves, It will copy the data from current_path to all_paths.
The grid goes like this:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
You can only move to a square you touch so from 0 you can move to 1, 4 and 5. And from 1 to 3, 4, 5, 6 etc.
The main idea is to copy the current_path to the next function call (recursive) so it would hold the curren_path up to that point, doing that until it’s full (10 steps). After it’s copied from current_path to all_paths I suppose I have to delete the current_path?
I know how to efficiently calculate all steps but I’m having trouble copying the current_path and propably and how do I add the current_path to all_paths when I’m at 10 steps?
There are a few problems with your code. By the end of line 4, you have two vectors that each contain 10 empty vectors. You could visualize it like this:
Those inner vectors still do not have any elements so when you try and set
a[0][0]to123, you’re accessing an element that doesn’t exist, invoking undefined behaviour.If that had worked, your use of
std::copywould simply copy each of the vectors fromaand pushed it to the back ofb. Sincebalready has 10 elements, it would now have 20 elements.Then you try to output
b[0][0]which doesn’t exist just as much asa[0][0]didn’t either.The solution here is to simply use the copy assignment operator defined by
std::vector: