简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM