二元&#39; [&#39; :&#39; std :: initializer_list <const char =“”* =“”>&#39;没有定义此运算符或转换为预定义运算符</const>可接受的类型

时间:2014-06-21 19:26:04

标签: c++ c++11 visual-studio-2013

如何使用auto关键字声明的初始值设定项访问值?

auto arr = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
auto a = arr[0];

在VS上提供以下编译错误:

  

二进制&#39; [&#39; :&#39; std :: initializer_list&#39;没有定义   此运算符或转换为预定义可接受的类型   操作

2 个答案:

答案 0 :(得分:3)

查看std::initializer_list

的界面
auto arr = { "one", "two", "three", "four", "five", "six",
              "seven", "eight", "nine" };
auto a = *arr.begin();

(或者,更实际的是,使用braced-init-list初始化容器或数组)

答案 1 :(得分:2)

您可以使用迭代器遍历初始化列表。函数begin()返回指向初始化列表中第一个元素的指针。

int main() {

    auto arr = { "one", "two", "three", "four", "five", "six",
              "seven", "eight", "nine" };
    auto a = *arr.begin();
    auto b = *( arr.begin() + 1);

    cout << a << "," << b; // prints: one,two

    return 0;
}