Rijuyuezhu
Rijuyuezhu

Reputation: 3

For C++ vector initialization, what's the difference between "vector<int>v = n;" and "vector<int>v(n);"

(English is not my native language; please excuse typing and grammar errors.)

I'm trying to create a vector<int> object with known length n.

I knew that I could do this by vector<int> v(n); or vector<int> v = vector<int>(n);. However, when I tried to do it by vector<int> v = n;, I got an Compile Error.

In my previous experience, vector<int> v = n seems the same as vector<int> v = vector<int>(n), but it proves that I'm wrong.

I've read the cpp reference and searched "C++ vector initialize with an integer" on stackoverflow but cannot find much useful information.

So what's the difference between the three ways? Thanks in advance.

Upvotes: 0

Views: 132

Answers (2)

user12002570
user12002570

Reputation: 1

Case 1

Here we consider the statement:

vector<int> v = n;  //this is copy initialization

The above is copy-initialization. But the constructor for std::vector that take size as argument is explicit and hence cannot be used here, and so this fails with the error that you're getting.

Case 2

Here we consider the statement:

vector<int> v = vector<int>(n); //this is also copy initialization

The above is also copy initialization. But this time, there is a copy constructor of std::vector that takes a vector as an argument and so this works without any error. Here the vector named v is created as a copy of(prior C++17) the temporary vector on the right hand side.

Also note that from C++17 onwards, due to mandatory copy elison, it is guaranteed that v is constructed directly using the ctor that takes an size as argument instead of being created as a copy using the copy ctor.

Case 3

Here we consider the statement:

vector<int> v(n); //this is direct initilaization

The above is direct initialization and it creates a vector named v of size n. This works because even though the ctor that takes size as argument is explicit, it can be used in direct initialization.

Upvotes: 1

Maple Q
Maple Q

Reputation: 21

vector<int> v(n) generate a vector named "v"

vector<int> v declare a vector named "v"

vector<int> v = vector<int>(n) means that you generate a temp vector<int>(n) and v = temp . "v" and "temp" have the same type vector<int> so you can use "=" on them.

But vector<int> v = n is vector<int> = int they don't have the same type.

Upvotes: 1

Related Questions