-4

I am trying to initialize an array of a vector of ints.

This is my code:

vector<int> *vec[] = new vector<int>[n+1];

I get the following compilation error:

initialization with '{...}' expected for aggregate object

What's wrong with this ?

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 5
    Why you want to mix and mingle STL containers and raw pointers is beyond me. But you need to remove the `[]` in the declaration. Probably. It's not really clear what you actually want to do. – Adrian Mole Dec 31 '22 at 06:59
  • The problem is that you're trying to initialize an array of pointers to vector with a "pointer to a vector". – Jason Dec 31 '22 at 07:03
  • 3
    I think you have a bit more of C++ to learn. In current C++ you [don't use new/delete yourself](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r11-avoid-calling-new-and-delete-explicitly) (unless you are writing datastructures). If you want n+1 integers all set to 0 use `std::vector values(n+1,0);` [An introduction to std::vector](https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdvector/). If you want to allocate memory yourself at least use [std::make_unique](https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique) – Pepijn Kramer Dec 31 '22 at 07:07
  • You may be under the mistaken assumption that `dsa` stands for Data Structures and Algorithms. It doesn't. using the `dsa` tag means you're asking about a public-key cryptographic signature algorithm. Always read the tag information before using a tag. – user4581301 Dec 31 '22 at 08:36
  • `vector *vec[]` is an array of pointers to vectors of int. – molbdnilo Dec 31 '22 at 09:54
  • `std::unique_ptr[]> vec{std::make_unique[]>(n + 1)};` — but anyway, please don’t do that; just nest it into another `vector`; problem solved. – Andrej Podzimek Jan 01 '23 at 02:37

2 Answers2

1

If you need an array (in the broad sense) of elements of type vector<int>, I advise you to use:

std::vector<std::vector<int>> vec(n+1);

vec will be a vector of vectors. The number of vectors will be n+1 like it seems you wanted. std::vector will manage the memory for you, so there's no need for new/delete.

In C++ we also have std::array, but it looks like the number of elements in vec is dynamically dependant on n, which makes a topmost std::vector the proper fit.

There are many advantages using C++ std::vector/std::array over C style arrays. See e.g. the answers here: std::vector versus std::array in C++.

If you must use a C style topmost array, see the other answer.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
0

The problem is that you're trying to initialize an array of pointers to vector with a "pointer to a vector".

To solve this you can either remove the [] from the left hand side of the declaration or not mix std::vector and raw pointers.

//--------------v----------------------->removed [] from here
vector<int> *vec = new vector<int>[n+1];
Jason
  • 36,170
  • 5
  • 26
  • 60