when I use this code:
int main()
{
unsigned int n;
cin >> n;
vector<int>number[n];
return 0;
}
the compiler mark '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)
and as vector<int> v2[n]
?
Do vectors use dynamic allocation?
and thanks in advance
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.