1

Hi I have a problem where at compile time, I don't know how many vectors in my program are needed. The number required depends on a data set given at run-time, which will results in the range of vectors needed to be from 1 to N.

So if the data set requires ten vectors, it will create vec1,vec2,......vecN

How can i dynamically create the vectors so that they all have a different name?

I would then need to call each array separately. Presumably I could just use strings and a few loops for this.

1
  • or you can use vector of vectors vector<vector<xxx>> v Commented Jul 23, 2012 at 11:32

3 Answers 3

5

You can't do that directly. However, you could use a map to store a vector name, and the vector itself:

map<string, vector<int> > myMap;

You can add elements simply like this (if the element with such key doesn't exist yet):

vector<int> vec;
myMap["vec"] = vec;

If you'll do it with a key that already exists, the value will be replaced. For example:

vector<int> vec;
vector<int> vec1;
myMap["vec"] = vec;
myMap["vec"] = vec1;//now myMap["vec"] holds the vec1 vector

You can also easlly access elements like this:

myMap["vec"]//this will access the vector with the key "vec1"
Sign up to request clarification or add additional context in comments.

2 Comments

I recommend using unordered_map to waste less resources.
@SingerOfTheFall I know this is not the appropriate place but I have no other way to contact you. You can't plagiarize 30+ tag wikis and expect to reap a bunch of rep for it. They're all soon to be rejected. I'll delete this comment shortly.
5

You can create a vector to contain your vectors:

std::vector<std::vector<int>> my_vector_of_vectors;

// Add a vector
my_vector_of_vectors.push_back(std::vector<int>{});

// Add a number to the inner vector
my_vector_of_vectors[0].push_back(1);

Comments

0

you have a vector of vectors, vec[0] to vec[n], each one containing the vector.

However, this works est if you know the number of vectors (eg 10). If you need to add new ones on-demand, then a list of vectors or a map might be a better option for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.