简体   繁体   English

C ++中的向量初始化17

[英]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]: 当我使用C ++ 17编译此代码时,它运行良好,但除了C ++ 17以外的任何版本都会引发错误[尝试使用C ++ 14]:

error: missing template arguments before 'v' 错误:'v'之前缺少模板参数
vector v {1, 2, 3}; 向量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? 在C ++ 17中是否更改了std::vector声明和/或初始化? Can anyone explain why C++17 compiles this vector initialization (as intended) without any error? 任何人都可以解释为什么C ++ 17编译此向量初始化(按预期)没有任何错误?

Prior to C++17 you MUST specify vector's type through template: 在C ++ 17之前,你必须通过模板指定vector的类型:

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. 相反,C ++ 17允许“演绎”,这就是为什么你的代码编译即使没有指定向量中包含的类型。 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. 一般来说,我建议指定类型的可读性,即使扣除会做你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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