-2
int n = 10;  
vector<int> adj[n];

Does this line create an array of vectors or a Vector of Arrays. And how is it different from

vector<vector <int>> vect;
6
  • 1
    As long n isn't a constant, the 1st code isn't valid c++. Commented Sep 18, 2022 at 17:03
  • 1
    Is the size n known at compile-time, and won't change of be updated at run-time? Then a std::array<std::vector<int>, n> could work (depending on the value of n and where adj is defined). Commented Sep 18, 2022 at 17:03
  • And a guess from my side: Are you using some kind of "competition" or "judge" site to learn C++? Such sites are not any kind of learning or teaching resource. They all require pretty good knowledge of the selected language and basic data-structures. If possible please invest in some good C++ books to learn it properly first. Commented Sep 18, 2022 at 17:06
  • "how is it different" is rather unfocussed. "What's the difference between an apple and an orange" invites someone to just talk endlessly about all the differences, perhaps without ever hitting on the one detail that makes you think they are similar. It would be better not to ask your question in an open-ended way. Do some experimenting to confirm or disprove your own understandings of what's happening, then come here to ask about any discrepancies or inconsistencies that you discover between your expectations and your actual results. Commented Sep 18, 2022 at 17:09
  • A vector's size can dynamically change over the lifespan of the vector object. A C-style array (or a C++ style std::array) has a fixed size known at compile-time. Some C++ compilers may implement C-style variable length arrays as a non-standard extension, but (if I understand correctly) that is fixed at runtime upon the creation of the array, and doesn't dynamically vary thereafter. Commented Sep 18, 2022 at 17:11

1 Answer 1

2
vector<int> adj[n];

Creates an array of n vectors of ints. However, if n is not a compile time constant, this is not standard C++, which does not support variable length arrays. Some compilers may implement it as an extension.

vector<vector<int>> vect;

This creates a vector of vectors of ints.

The dimensions of the latter are no longer fixed, which makes them functionally quite different. vect can contain any number of vector<int> values.

There are also significant ramifications to using std::vector or std::array vs. raw arrays when it comes to passing results to/from functions.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.