C++11 新特性:std::array

std::array是 C++11 中引入的容器类型,它封装了固定大小的数组,提供了类似于 STL 容器的接口,同时保持了 C 风格数组的性能特性。

与普通数组相比,std::array更安全、更易于使用,并且支持迭代器。以下是std::array提供的一些主要方法:

容量相关

  • empty():检查容器是否为空(即是否包含元素)。
  • size():返回容器中元素的数目。
  • max_size():返回容器可容纳的最大元素数目,对于std::array来说,这与size()相同。

元素访问

  • operator[]:访问指定位置的元素,不进行边界检查。
  • at():访问指定位置的元素,带有边界检查,如果索引越界,会抛出std::out_of_range异常。
  • front():返回容器中的第一个元素的引用。
  • back():返回容器中的最后一个元素的引用。
  • data():返回指向容器中第一个元素的指针。

修改器

  • fill():将容器中所有元素设置为某个特定值。
  • swap():与另一个std::array对象交换内容。

迭代器

  • begin()end():返回指向容器第一个元素和尾后元素的迭代器。
  • rbegin()rend():返回指向容器最后一个元素和头前元素的反向迭代器。
  • cbegin()cend()crbegin()crend():分别返回上述迭代器的常量版本。

示例代码

#include <array>
#include <iostream>

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};

    // 使用下标访问
    std::cout << "Element at index 2: " << arr[2] << std::endl;

    // 使用at()访问
    try {
        std::cout << "Element at index 4: " << arr.at(4) << std::endl;
        // 下面的代码会抛出 std::out_of_range 异常
        std::cout << "Element at index 5: " << arr.at(5) << std::endl;
    } catch (std::out_of_range& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    // 修改元素
    arr.fill(10);
    std::cout << "After fill(10):";
    for (int i : arr) {
        std::cout << " " << i;
    }
    std::cout << std::endl;

    // 迭代器遍历
    std::cout << "Elements:";
    for (auto it = arr.begin(); it != arr.end(); ++it) {
        std::cout << " " << *it;
    }
    std::cout << std::endl;

    return 0;
}

输出:

Element at index 2: 3
Element at index 4: 5
Element at index 5: Error: array::at: __n (which is 5) >= _Nm (which is 5)
After fill(10): 10 10 10 10 10
Elements: 10 10 10 10 10

std::array通过提供 STL 容器的接口,使得固定大小数组的使用更加灵活和安全。在需要固定大小数组,且希望利用STL容器特性时,它是一个非常有用的类型。

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值