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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With