C ++: building std :: vector <std :: vector <int>> with a two-dimensional C array?

A std :: vector can be constructed using the C-array as follows: std::vector<int> vec(ary, ary + len). What is the correct way to build std::vector<std::vector<int> >?

I rudely forced the problem to manually copy each element into a vector, it is clear that this is not an intention, 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];
    }
}
+3
source share
2 answers
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 change the last line as follows to remove a little noise:

    m.emplace_back(map[i], map[i] + 25);
+6
source

? , . , matrix, std::vector<int> 18*25 (operator()( int, int )) , col + row*columns...

++ FAQ lite .

+4

All Articles