Search code examples
c++integerpush-back2d-vector

Why can't I push a vector of integers to a 2-D vector of integers in C++?


Here is my 2D vector of integers.

vector<vector<int>> nodes (r*c, vector<int> (5));

using a for loop I am trying to push_back values in this vector. r and c are passed integers to this function.

for(i = 0; i < r*c; i++)

{        
       nodes[i].push_back({i/c, i%c, -1, -1, 0});

}

Solution

  • nodes[i] is a vector of integers. You're trying to append a vector to a vector of integers.

    Either do:

    nodes.push_back({i/c, i%c, -1, -1, 0});
    

    or

    nodes[i] = {i/c, i%c, -1, -1, 0};
    

    The second solution being the best since you already gave the proper dimension to your vector. No need to add r*c more elements...

    in your code, either create empty, and populate with push_back:

    std::vector<std::vector<int>> nodes;
    for(i = 0; i < r*c; i++)
    {        
       nodes.push_back({i/c, i%c, -1, -1, 0});
    }
    

    or create with proper dimension and assign items:

    std::vector<std::vector<int>> nodes (r*c, std::vector<int> (5));
    for(i = 0; i < r*c; i++)
    {        
       nodes[i] = {i/c, i%c, -1, -1, 0};
    }