访问数组元素,并进行赋值
int cnt = 0;
for (auto& x : arr2) {
x = cnt++ * 1.1;
}
// 用迭代器访问数组元素
for (auto it = arr2.begin(); it != arr2.end(); it++) { // 输出:0 1.1 2.2 3.3
cout << *it << ' ';
}
cout << endl;
// 创建一个存储 3 个 string 类型元素的数组 arr3,用 {} 初始化列表进行赋值
array<string, 3> arr3 = {"hello", "world", "!"};
// 用 auto 关键字快速 for 循环遍历数组元素
for (const auto& s : arr3) { // 输出:hello world !
cout << s << ' ';
}
cout << endl;
// 使用 at() 函数访问数组元素,如果下标越界则抛出异常
arr1.at(10) = 100; // 抛出 std::out_of_range 异常
/* 输出:terminate called after throwing an instance of 'std::out_of_range'
what(): array::at: __n (which is 10) >= _Nm (which is 5) */
return 0;
}
|