Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `vector<int> v;` and `vector<int> v = vector<int>();`

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?

like image 229
Remi.b Avatar asked Mar 01 '19 03:03

Remi.b


People also ask

What is the difference between vector INT and vector int []?

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.

What is meaning of vector vector int >>?

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.

Does vector size () return an int?

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 .

What is difference between list and vector?

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.


1 Answers

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); }; 
like image 128
AnT Avatar answered Oct 01 '22 13:10

AnT