0

To create a dynamically-allocated array, I use:

int *x = new int[100];

This creates an array of 100 int elements.

However, if I use:

std::vector<int> *x = new vector<int>(100);

This also creates an array of 100 int elements. But why does it not create an array of 100 vector<int> elements? And how would I go about doing that?

1
  • You have used () instead of []. I have added an answer which shows how to dynamically allocate an array of vectors, although I am not sure if that is what you really want. Commented Mar 31, 2015 at 1:02

3 Answers 3

9

In order to achieve what you want you need to do:

std::vector<int> *x = new vector<int>[100];

This will dynamically allocate array of 100 vectors, each vector will be default-constructed.

Sign up to request clarification or add additional context in comments.

Comments

5

If you want to create an 100 vectors each containing 100 integers, just use multiple (nested) vectors:

std::vector<std::vector<int> > x(100, std::vector<int>(100));

Comments

-1

You need to declare the variable as a vector of vectors, rather than a vector of integers.

std::vector<vector<int>> *x = new vector<vector<int>>(100);

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.