You are using a version without Ads of this website. Please, consider donating:

### how to declare number of vectors dynamically

I need to declare the number of vectors according to an input parameter call NUM HOST.
for example, if NUMHOST=4, I need to declare 4 vectors and the name of the vectors seriam: vector1, vector2, vector3, in struct for would be vectori...

for (int i = 0; i <= NUMHOST; i++)
int vector????[3];
I suggest nesting vectors.

 ``123`` ``````std::vector> v; for (int i = 0; i < NUMHOST; ++i) v.emplace_back();``````
Yeah, store the vectors in a vector. But you don't have to use a loop.Instead you can pass the size of the vector to the constructor.
`std::vector<std::vector<YourClass>> v(NUMHOST);`
Last edited on
@Peter87

You are very right! My loop would be terribly inefficient; especially when NUMHOST → ∞ compared to your version (or resize()).

 ``1234567891011`` ``````#include int main() { enum {NUMHOST = 4}; std::vector> v(NUMHOST); v.at(3).push_back(12); // for (int i = 0; i < NUMHOST; ++i) // v.emplace_back(); } ``````
I believe that I can not use vector of vectors because I'm programming a distributed system and each node should only be aware of your information and not the information global network, so I have to have a vector only.
I don't understand your logic, how is that relevant to whether you use a vector of vectors or not? Alternatives are far and few.
It should not matter, as long as you don't share information that is not necessary.

 ``123456789101112`` ``````int do_something_to_a_vector( std::vector & v ) { // this function only knows about v } int main() { // The list of vectors std::vector > vs( n ); ... do_something_to_a_vector( vs[ 2 ] ); ...``````
I try declare the function do_something_to_a_vector, but when I call the function "do_something_to_a_vector (vs [2]), ocurrs the following error:

no matching function for call to do_something_to_a_vector(int&)'

Also I not understand what would be the parameter 2, would be the index the vector?
thanks.
Is vs declared like on line 9 of Duoas' code?
thanks, now is all right, however, I not understand:

1- what is "vs[ 2 ]?"

2- how assign values to vs???
vs is a vector that contains other vectors. vs[2] is the third vector it contains.
I understand,thanks, but I try assign values para v[a], but don't get, I try:

v[1]=1;

v.at(0).at(0) =1;

v.at(1).push_back(1);

` std::vector <std::vector <int> > vs( n );`
creates a vector of n empty vectors. These vectors must be populated before you can access elements of those vectors.

` std::vector<std::vector<int>> vs(n, std::vector<int>(m))`
creates a vector of n vectors of m elements.

 ``1234567891011121314151617181920212223`` ``````#include #include #include void print(const std::vector & v) { for ( unsigned i=0; i > vs( n, std::vector(m) ); for ( unsigned i=0; i
Last edited on
thanks,
works!!
Topic archived. No new replies allowed.

You are using a version without Ads of this website. Please, consider donating: