#include <vector>
#include <iostream>
int main()
{
std::vector<std::vector<int> > vRows;
for (int r=1; r<6; r++)
{
std::cout << "values= ";
for (int c=1; c<3; c++)
{
int value = r*10 + c;
std::cout << value << " ";
vRows.push_back(value); //compile error
}
std::cout << std::endl;
}
for (auto& itRow : vRows)
{
std::cout << "cells = ";
for (auto& itCell : itRow)
{
std::cout << itCell << " ";
}
std::cout << std::endl;
}
}
compile error:
1 2 3 4
$ g++ vector_2D.cpp
vector_2D.cpp: In function βint main()β:
vector_2D.cpp:25:34: error: no matching function for call to βstd::vector<std::vector<int> >::push_back(int&)β
vRows.push_back(value);
vRows is a vector<vector<int>> you need to push a vector<int> not an int into this vector.
Something like:
1 2 3 4 5 6 7 8 9 10 11 12 13
for (int r=1; r<6; r++)
{
std::cout << "values= ";
vector<int> temp;
for (int c=1; c<3; c++)
{
int value = r*10 + c;
std::cout << value << " ";
temp.push_back(value); // Push the int into the temporary vector<int>
}
std::cout << std::endl;
vRows.push_back(temp);
}
By the way you really should start getting used to the fact that C++ uses zero based arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
for (int r = 0; r < 5; r++)
{
std::cout << "values= ";
std::vector<int> tempCells;
for (int c = 0; c < 2; c++)
{
int value = r * 10 + c;
std::cout << value << " ";
tempCells.push_back(value); // Push the int into the temporary vector<int>
}
std::cout << std::endl;
vRows.push_back(tempCells);
}
Vectors or Arrays in C++ start at zero and stop at size - 1, element 0 is the first element, not element 1.