0

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});

}
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Ishrat
  • 27
  • 1

2 Answers2

0

Use method insert instead of push_back

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

But before this you should declare the vector like

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

Otherwise first 5 elements of each subvector will contain zeroes.

Also you can use method assign

nodes[i].assign(  {i/c, i%c, -1, -1, 0});
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • that's not the problem. `nodes[i]` is a vector of _integers_. You cannot insert a vector in it. That's why `push_back` fails (and `insert` compiles but god knows what it does. Segfault here) – Jean-François Fabre Nov 09 '16 at 22:24
  • @Jean-FrançoisFabre Нщг You are wrong. It is not a vector that is inserted . It is values of the initializer list that are inserted. – Vlad from Moscow Nov 09 '16 at 22:26
  • I still have a doubt, and you obviously did not test that because that `nodes[i].insert( nodes[I].end(), {i/c, i%c, -1, -1, 0});` does not compile (`I` is undeclared). Also `nodes.insert( nodes.end(), {i/c, i%c, -1, -1, 0});` compiles! – Jean-François Fabre Nov 09 '16 at 22:58
  • @Jean-FrançoisFabre I do not know what you compiled. It is a valid code. Maybe your old compiler does not support C++ 11. – Vlad from Moscow Nov 09 '16 at 23:05
  • `I` is uppercase. It is _not_ valid code. And my compiler supports C++11, and your code compiles (after fixing the `I` stuff) but doesn't work. Try printing `nodes[0][2]` after your insertion you'll get `0`. I get `-1` as expected. – Jean-François Fabre Nov 09 '16 at 23:08
  • @Jean-FrançoisFabre One again I do not know what you are compiling. This program is valid #include #include int main() { std::vector> v( 1 ); v[0].insert( v[0].end(), { 1, 2, 3, 4, 5 } ); for ( int x : v[0] ) std::cout << x << ' '; std::cout << std::endl; return 0; } – Vlad from Moscow Nov 09 '16 at 23:12
0

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};
}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219