如何使用auto
关键字声明的初始值设定项访问值?
auto arr = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
auto a = arr[0];
在VS上提供以下编译错误:
二进制' [' :' std :: initializer_list'没有定义 此运算符或转换为预定义可接受的类型 操作
答案 0 :(得分:3)
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;
}