Reputation: 13
I am trying to initialize vectors depending upon user input. For example, if user provide n=4
then I have to create 4 vectors of varying sizes.
As for vectors syntax is :
vector<int> v1(x);
So, similarly I want to create v2
,v3
and v4
named vectors.
I am confused. How can I do this ?
Upvotes: 1
Views: 2088
Reputation: 22152
The names of individual vectors v1
, v2
, v3
, ... are defined at compile time. If you want to have a dynamic number of vectors, you need a vector
of vector
s, e.g.:
std::vector<std::vector<int>> vs;
or if you already know the number of vectors n that you want:
std::vector<std::vector<int>> vs(n);
Then, instead of using v1
, v2
, v3
, you'd use vs[0]
, vs[1]
, vs[2]
, and your code could use dynamically a vector v[i]
where i
is a variable or an expression.
You can add a vector to vs
with emplace_back
/push_back
or resize
:
vs.emplace_back();
//or
vs.push_back({});
// or
vs.push_back(std::vector<int>());
// or
vs.resize(4);
In the latter case vs
will contain four empty vectors (or the first 4 existing vectors if vs already had more than 4 vectors).
And you can add elements to the inner vectors as usually, e.g.:
vs[0].push_back(42);
vs[2].resize(x);
After that the first vector will have length one and the third vector will have length x
.
Or you can insert a vector with size x
directly after the last vector:
vs.emplace_back(x);
// or
vs.push_back({x});
// or
vs.push_back(std::vector<int>(x));
Elements can then be accessed with double indices, e.g.
vs[1][14]
reads the 15th element of the 2nd vector.
Upvotes: 6