C++学习随笔——C++11的array、forward_list、tuple的用法

1. std::array

std::array 是 C++11 引入的一个封装了原生数组的容器,它结合了 C++ 标准库容器的优点和 C 风格数组的效率。

#include <array>
#include <iostream>

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5}; // 初始化一个大小为5的数组

    // 访问元素
    for (int i = 0; i < arr.size(); ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // 使用范围基于 for 循环
    for (const auto& elem : arr) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    // 获取数组大小
    std::cout << "Size of array: " << arr.size() << std::endl;

    // 使用at()方法进行边界检查
    try {
        std::cout << arr.at(10) << std::endl; // 这将抛出一个 std::out_of_range 异常
    } catch (const std::out_of_range& e) {
        std::cout << e.what() << std::endl;
    }

    return 0;
}

特点

  • 固定大小std::array 的大小在编译时确定,并且不能动态调整。
  • 性能:相比于 std::vectorstd::array 没有额外的内存分配开销。
  • 安全性:提供了边界检查的 at() 方法,使用时可以避免越界访问。

 

2. std::forward_list

std::forward_list 是一种单向链表,C++11 引入它是为了提供一个轻量级的链表替代方案,适用于只需单向遍历的场景。

#include <forward_list>
#include <iostream>

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

    // 插入元素到链表前面
    flist.push_front(0);

    // 遍历链表
    for (const auto& elem : flist) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    // 插入元素到指定位置后面
    auto it = flist.begin();
    flist.insert_after(it, 10);

    // 删除元素
    flist.remove(3);

    for (const auto& elem : flist) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

特点

  • 单向链表std::forward_list 只支持单向遍历和单向插入删除操作,相比于 std::list 节省了内存。
  • 内存效率:由于 std::forward_list 只存储前向指针,因此比 std::list 更加节省内存,但也限制了它的操作(无法进行双向遍历)。

 

3. std::tuple

std::tuple (元组)是 C++11 引入的一个通用的数据结构,用于将多个不同类型的值组合在一起。它类似于 std::pair,但可以包含任意数量的元素。

#include <tuple>
#include <iostream>
#include <string>

int main() {
    // 创建一个 tuple
    std::tuple<int, double, std::string> myTuple = std::make_tuple(1, 2.5, "Hello");

    // 获取 tuple 的元素
    std::cout << "First element: " << std::get<0>(myTuple) << std::endl;
    std::cout << "Second element: " << std::get<1>(myTuple) << std::endl;
    std::cout << "Third element: " << std::get<2>(myTuple) << std::endl;

    // 使用 std::tie 解包 tuple
    int a;
    double b;
    std::string c;
    std::tie(a, b, c) = myTuple;

    std::cout << "a: " << a << ", b: " << b << ", c: " << c << std::endl;

    // 比较两个 tuple
    std::tuple<int, double, std::string> anotherTuple = std::make_tuple(1, 2.5, "World");
    if (myTuple < anotherTuple) {
        std::cout << "myTuple is less than anotherTuple" << std::endl;
    }

    return 0;
}

特点

  • 多值组合std::tuple 可以组合多个不同类型的值,是 std::pair 的扩展。
  • 解包功能:可以使用 std::tie 或结构化绑定(C++17 引入)来解包 tuple 的值。
  • 比较运算符std::tuple 支持比较运算符,可以直接比较两个 tuple 的大小。
posted @   北宸于烁  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示