首页 > 编程技术 > C语言

C++ Boost Container库示例详细讲解

发布时间:2022-11-8 11:17 作者:无水先生

一、关于Boost.Container

Boost.Container

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

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

二、Boost.Container示例

示例 20.1 说明了不完整的类型。

注意

本章中的示例无法使用 Visual C++ 2013 和 Boost 1.55.0 编译。此错误在工单 9332 中进行了描述。它已在 Boost 1.56.0 中修复。

示例 20.1。带有 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::vector<animal> 的成员变量 children。 boost::container::vector 在头文件 boost/container/vector.hpp 中定义。因此,成员变量children 的类型基于定义变量children 的类animal。在这一点上,还没有完全定义动物。虽然该标准不要求标准库中的容器支持不完整类型,但 Boost.Container 明确支持递归容器。标准库定义的容器是否可以递归使用取决于实现。

示例 20.2。使用 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 还提供容器。示例 20.2 引入了容器 boost::container::stable_vector,其行为类似于 std::vector,除了如果 boost::container::stable_vector 更改,所有迭代器和对现有元素的引用仍然有效。这是可能的,因为元素没有连续存储在 boost::container::stable_vector 中。即使元素没有彼此相邻存储在内存中,仍然可以使用索引访问元素。

Boost.Container 保证示例 20.2 中的引用 i 在向量中的第一个元素被擦除时仍然有效。该示例显示 1。

请注意,boost::container::stable_vector 和该库中的其他容器都不支持 C++11 初始化列表。在示例 20.2 中,v 被初始化为两个元素都设置为 1。

boost::container::stable_vector 在 boost/container/stable_vector.hpp 中定义。

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

boost::container::static_vector 在 boost/container/static_vector.hpp 中定义。

到此这篇关于C++ Boost Container库示例详细讲解的文章就介绍到这了,更多相关C++ Boost Container内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://yamagota.blog.csdn.net/article/details/127417000

标签:[!--infotagslink--]

您可能感兴趣的文章: