A std::vector can be constructed using a C-array like so: std::vector<int> vec(ary, ary + len). What is the proper way to construct a std::vector<std::vector<int> >?
I've been brute-forcing the issue by manually copying each element into the vector, clearly this is not the intent, but it works.
int map[25][18] = { /*...DATA GOES HERE...*/ }
std::vector<std::vector<int> > m(18, std::vector<int>(25, 0));
for(int y = 0; y < 18; ++y) {
for(int x = 0; x < 25; ++x) {
m[y][x] = map[y][x];
}
}
int map[18][25] = { /*...DATA GOES HERE...*/ };
std::vector<std::vector<int> > m;
m.reserve(18);
for (std::size_t i = 0; i != 18; ++i)
m.push_back(std::vector<int>(map[i], map[i] + 25));
In C++11, you can optionally replace the last line with the following to remove a little noise:
m.emplace_back(map[i], map[i] + 25);
Why do you want to do that? You have a contiguous block of memory and you are turning that into multiple blocks of memory. I would suggest that rather than that you provide a matrix class that encapsulates the contents of a single std::vector<int> of size 18*25 and provides accessors (operator()( int, int )) for the elements that accesses col + row*columns...
More in the C++ FAQ lite entry for operator overloading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With