What is the difference between
std::vector<int> v;
and
std::vector<int> v = std::vector<int>();
Intuitively, I would never use the second version but I am not sure if there is any difference. It feels to me that the second line is simply a default constructor building a temporary object that is then moved by a move assignment operator.
I am wondering whether the second line is not somehow equivalent to
std::vector<int> v = *(new std::vector<int>());
hence causing the vector itself to be on the heap (dynamically allocated). If it is the case, then the first line would probably be preferred for most cases.
How do these lines of code differ?
vector V[] is just a fixed array; and so you can add/modify only till the upper limit. It is not a vector per se, and so has a fixed size limit. However vector< vector > V is a dynamic vector and its size can be increased dynamically.
elements each having the value "vector<int> (m, 0)". "vector<int> (m, 0)" means a vector having "m" elements each of value "0". Here these elements are vectors.
size() returns a size_t type value, which is an alias for unsigned long int . In plain terms: unsigned long int a=0; cout<<a-1; The above code will give the same result — 18446744073709551615 .
A list holds different data such as Numeric, Character, logical, etc. Vector stores elements of the same type or converts implicitly. Lists are recursive, whereas vector is not. The vector is one-dimensional, whereas the list is a multidimensional object.
Starting from C++17 there's no difference whatsoever.
There's one niche use case where the std::vector = std::vector
initialization syntax is quite useful (albeit not for default construction): when one wants to supply a "count, value" initializer for std::vector<int>
member of a class directly in the class's definition:
struct S { std::vector<int> v; // Want to supply `(5, 42)` initializer here. How? };
In-class initializers support only =
or {}
syntax, meaning that we cannot just say
struct S { std::vector<int> v(5, 42); // Error };
If we use
struct S { std::vector<int> v{ 5, 42 }; // or = { 5, 42 } };
the compiler will interpret it as a list of values instead of "count, value" pair, which is not what we want.
So, one proper way to do it is
struct S { std::vector<int> v = std::vector(5, 42); };
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