1

when I use this code:

int main()
{
    unsigned int n;
    cin >> n;
    vector<int>number[n];
  
    return 0;
}

the compiler marks 'n' as an error:
"expression must have a constant value"
"the value of variable 'n' cannot be used as a constant"

but when I use vector<int> v1(n) instead, the error disappeared and worked well.

so, here is my questions:
what is the difference between defining a vector as vector<int> v1(n) vs vector<int> v2[n] ?
Do vectors use dynamic allocation?

Thanks in advance

Huster
  • 43
  • 2
  • 5
    The difference is that one is a vector and one is an __array__ of vectors. – tkausl Dec 09 '21 at 01:03
  • Also, because `n` is dynamically read in at runtime, the code is invalid C++. For a C-style array it needs to be a constant (`const` or `constexpr`). – Eljay Dec 09 '21 at 01:10
  • Terminology note: Anything that can change size or shape is dynamic. That said, nothing in C++ ever really changes size. `vector` is always the same size. The array it points to never changes size. What happens is when vector needs a different sized array, it makes a new array, copies the old array into it, frees the old array and points at the new array. Nothing changed size, it just got replaced. – user4581301 Dec 09 '21 at 01:15

2 Answers2

1
type_name variable_name[array_size];

Is syntax for a default initialised array variable. vector<int>number[n]; is an array of n vectors. If the size is not compile time constant - such as it isn't in the example, then the program is ill-formed as evidenced by the error that you quoted.

type_name variable_name(args);

Is syntax for direct initialisation of a variable.

Do vectors use dynamic allocation?

As with most standard containers (all except std::array), vector elements are dynamic objects. It acquires the storage using the allocator that has been provided to it.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

Difference between the two definitions

  • vector<int> v1(n) defines a single vector that contains n elements.

  • vector<int> v2[n] defines a variable sized array of vectors, each of which will contain no elements. This is commonly called a VLA (Variable Length Array) and not officially part of C++ (it is part of C99 however). Some compilers like gcc do support it for c++ as well, but you shouldn't count on it.

std::vector allocation

std::vectors will allocate their elements with the provided allocator (the second template argument std::vector<T,Allocator>).

By default this will be std::allocator<T>, which will use new & delete - i.e. it'll be allocated on the free store (mostly implemented as a heap).

You can provide a different allocator though if you want to use some other allocation strategy (heres what you would need to implement for a custom allocator)

Turtlefight
  • 9,420
  • 2
  • 23
  • 40