boost::container

Boost.Container 提供与标准库相同的容器,专注于额外的灵活性。例如,这个库中的所有容器都可以在共享内存中与 Boost.Interprocess 一起使用——这对于标准库中的容器并不总是可行。

Boost.Container 提供了额外的优势:

  • 容器的接口类似于 C++11 标准库中容器的接口。例如,它们提供诸如 emplace_back() 之类的成员函数,可以在 C++98 程序中使用它,即使它直到 C++11 才被添加到标准库中。
  • 借助 boost::container::slist 或 boost::container::stable_vector,Boost.Container 提供了标准库不提供的容器。
  • 该实现与平台无关。容器在任何地方的行为都相同。您无需担心标准库实现之间可能存在的差异。
  • Boost.Container 中的容器支持不完整的类型,可用于定义递归容器。

Boost.Container 的递归容器
Boost.Container 明确支持递归容器。标准库定义的容器是否可以递归使用取决于实现。

#include <boost/container/vector.hpp>
 
using namespace boost::container;
 
struct animal
{
  vector<animal> children;
};
 
int main()
{
  animal parent, child1, child2;
  parent.children.push_back(child1);
  parent.children.push_back(child2);
}

boost::container::stable_vector

#include <boost/container/stable_vector.hpp>
#include <iostream>
 
using namespace boost::container;
 
int main()
{
  stable_vector<int> v(2, 1);
  int &i = v[1];
  v.erase(v.begin());
  std::cout << i << '\n';
}

boost::container::stable_vector,其行为类似于 std::vector,即使元素没有彼此相邻存储在内存中,仍然可以使用索引访问元素。

Boost.Container 提供的其他容器是 boost::container::flat_set、boost::container::flat_map、boost::container::slist 和 boost::container::static_vector:

  1. boost::container::flat_set 和 boost::container::flat_map 类似于 std::set
    和 std::map。然而,它们被实现为排序向量,而不是树。这允许更快的查找和迭代,但插入和删除元素的成本更高。这两个容器在头文件 boost/container/flat_set.hpp 和 boost/container/flat_map.hpp 中定义。
  2. boost::container::slist 是一个单链表。它类似于使用 C++11 添加到标准库的
  3. std::forward_list。 boost::container::slist 提供了一个成员函数 size(),它在
    std::forward_list 中没有。
  4. boost::container::slist 在 boost/container/slist.hpp 中定义。
  5. boost::container::static_vector 将 std::array 等元素​​直接存储在容器中。与
    std::array 一样,容器具有恒定的容量,尽管容量并没有说明元素的数量。成员函数
    push_back()、pop_back()、insert() 和erase() 可用于插入或删除元素。在这方面,
    boost::container::static_vector 类似于 std::vector。成员函数 size()
    返回容器中当前存储元素的数量。
  6. 容量是恒定的,但可以使用 resize() 更改。 push_back() 不会改变容量。仅当容量大于当前存储的元素数量时,您才可以使用
    push_back() 添加元素。否则,push_back() 会抛出 std::bad_alloc 类型的异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值