0

(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.

  • Read about `explicit` constructors. – jxh Sep 02 '22 at 04:09
  • This is explained in any beginner level [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Sep 02 '22 at 04:36

2 Answers2

1

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.

Maple Q
  • 21
  • 3
  • https://tio.run/##Sy4o0E1PTv7/v7ikqDS5RCEktbhEoZpLAQgy80oU8uKtwWywsAZYRFPBCiisAaSra7lqrbn@g0RzEzPzFDQ0oTrBqksUbBVMrLlquf4DAA – jxh Sep 02 '22 at 04:38
  • Actually with C++17 mandatory copy elision, there is no temporary created in `vector v = vector(n)`. – Jakob Stark Sep 02 '22 at 05:31
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.

Jason
  • 36,170
  • 5
  • 26
  • 60