#include <iostream>
#include <array>
int main() {
// 定义一个包含5个整数的数组
std::array<int, 5> arr = {1, 2, 3, 4, 5};
// 输出数组中的元素
for (size_t i = 0; i < arr.size(); ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// 使用at()方法访问数组元素(带边界检查)
try {
std::cout << "Element at index 2: " << arr.at(2) << std::endl;
std::cout << "Element at index 10: " << arr.at(10) << std::endl; // 这将抛出异常
} catch (const std::out_of_range& e) {
std::cout << "Error: " << e.what() << std::endl;
}
// 使用fill()方法填充数组
arr.fill(0);
std::cout << "After filling with 0s: ";
for (const auto& elem : arr) {
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
std::array<int, 5> arr = {1, 2, 3, 4, 5}; 定义了一个包含5个整数的数组,并初始化为1到5。for循环遍历数组并输出每个元素。at()方法:arr.at(2) 访问索引为2的元素,arr.at(10) 会抛出std::out_of_range异常,因为索引超出了数组范围。fill()方法:arr.fill(0) 将数组中的所有元素设置为0。try-catch块捕获并处理std::out_of_range异常。上一篇:c和c++
下一篇:c++高并发
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站