I have a vector and want to store int data in to it at run time can I store the data in a 2D vector in this manner ?
std::vector> n
You are manipulating a vector of vectors.
As such, when declaring normal
it is empty and does not contain any element.
You can either :
std::vector > normal;
normal.resize(20);
for (size_t i = 0; i < normal.size(); ++i)
{
for (size_t j = 0; j < 20; ++j)
normal[i].push_back(j);
}
This may be slightly more efficient than pushing an empty vector at each step as proposed in other answers.
If you want to store a 2D array, this is not the optimal solution, because :
normal[i].size() == normal[j].size()
Instead, you can use a vector of size N * M
(where N
is the number of lines and M
the number of columns), and access an element at line i
and columns j
using the index i + j * N
:
size_t N = 20;
size_t M = 20;
std::vector normal;
normal.resize(N * M);
for (size_t i = 0; i < N; ++i)
for (size_t j = 0; j < M; ++j)
normal[i + j * N] = j;