Loading

Array的简单使用(Boost和STL通用)

目录

介绍

本来这一次是想简单介绍一下Boost里面的协程库的使用的,但是Boost.Coroutine已经被废弃了,而Boost.Coroutine2目前只有非对称的协程支持,个人感觉并不是特别具有使用的价值。而C++20中的协程,IDE对其的支持并不是特别好,代码报错异常多,因此我打算在完全摸透后再考虑写这一部分的内容。

Boost.Array目前来说,和之前的Boost.Random一样,都进入了C++11的标准中。因此,其作者推荐如果使用了C++11,那么最好使用标准库中的Array而不是Boost中的。而本文虽然主要介绍Boost.Array,但是也会对C++11中的进行一些讲解,同时对他们进行对比。

Boost.Array的提出,主要是因为在当时,STL中并没有一个具有C++风格的,固定大小的容器。如果需要使用一种类似于C语言中数组的容器,开发者一般会直接使用C语言中的数组或者是使用std::vector。而C中的数组对于C++来说,略显不优雅;而std::vector由于是动态的,相对来说性能上会有不必要的损失,也没办法在模板中使用(C++20中,std::vector可以使用在模板中,而且支持大部分的函数)。

使用

Boost.Array是一个模板,需要两个模板参数,分别是数据的类型和数组的大小。

boost::array<int, 1024> temp_array;

由于是模板参数,所以数组的大小必须是一个可以在编译阶段就可以推理得到的值。定义以后,就可以正常使用了。其使用方法和std::vector较类似。

// 使用某个数字填满
temp_array.fill(1);

// 迭代
for (auto temp_iter = temp_array.begin(); temp_iter != temp_array.end(); ++temp_iter) {
    *temp_iter = 2;
}

// 取某个元素
std::cout << temp_array[2] << " " << temp_array.at(3) << std::endl;
  
// foreach
int sum_array = 0;
for (auto temp_item : temp_array) {
    sum_array += temp_item;
}
std::cout << sum_array << std::endl;

// 逆序遍历
for (auto temp_iter = temp_array.rbegin(); temp_iter != temp_array.rend(); ++temp_iter) {
    *temp_iter = (temp_iter - temp_array.rbegin());
}
std::cout << temp_array[10] << std::endl;

// 一些属性
std::cout << temp_array.size() << " " << temp_array.max_size() << " " << temp_array.empty() << std::endl;

其中,sizemax_size只返回数组的大小。而empty只在数组大小为0时返回false,在其他时候返回true

Boost和STL的区别

STL中的Array在高版本的C++中,会支持更多的constexpr,如果使用在模板中会更加的方便。

为了支持更低版本的C++,Boost使用了模板偏特化来处理数组大小为0的情况。

Boost中有一个assign函数,功能和fill一样,但是STL中没有。

原博客地址:https://www.cnblogs.com/ink19/p/Boost_Array.html

posted @ 2020-12-11 15:51  ink19  阅读(577)  评论(0编辑  收藏  举报