Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "auto x = vector<int>()" and "vector<int> x"?

What is the difference between:

auto x = vector<int>(); 

and

vector<int> x; 

Are both of these declarations equivalent, or is there some difference with the run-time complexity?

like image 625
Autoratch Avatar asked Apr 16 '19 03:04

Autoratch


People also ask

What is the meaning of vector int?

Vectors in C++ are sequence containers representing arrays that can change in size. They use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays.

What is the use of vector int in C++?

In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library.

Is Vector better than array C++?

Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.

What is vector int V in C++?

vector<int> v[] is an array of vectors. That is, it is an array which contains vectors as its elements. So, you cannot change the size of the array part, but we can add to its elements which is vector.


1 Answers

They have the same effect since C++17. Both construct an object named x with type std::vector<int>, which is initialized by the default constructor of std::vector.

Precisely the 1st one is copy initialization, x is copy-initialized from a value-initialized temporary. From C++17 this kind of copy elision is guaranteed, as the result x is initialized by the default constructor of std::vector directly. Before C++17, copy elision is an optimization:

even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:

The 2nd one is default initialization, as a class type x is initialized by the default constructor of std::vector.

Note that the behaviors might be different for other types, depending on the type's behavior and x's storage duration.

like image 95
songyuanyao Avatar answered Sep 20 '22 11:09

songyuanyao