Deep
Deep

Reputation: 646

Vector initialization in C++17

When I compile this code with C++17 it works well, but any version other than C++17 it throws an error [tried with C++14]:

error: missing template arguments before ‘v’
vector v {1, 2, 3};

Here is the code snippet I am using:

#include <vector>
#include <iostream>

using std::vector;
using std::cout;

int main() {

    // Vector initialization
    vector v {1, 2, 3};

    for (int i=0; i < v.size(); i++) {
      cout << v[i] << "\n";
    }
}

Has std::vector declaration and/or initialization changed in C++17? Can anyone explain why C++17 compiles this vector initialization (as intended) without any error?

Upvotes: 4

Views: 4018

Answers (1)

Barnack
Barnack

Reputation: 941

Prior to C++17 you MUST specify vector's type through template:

std::vector<int> v{1, 2, 3};

C++17 instead allows for "deduction", which is why your code compiles even without specifying the type contained in your vector. You can read more about it here.

Generally I'd suggest to specify the type for readability even if deduction would do what you want it to.

Upvotes: 5

Related Questions