1. 程式人生 > 實用技巧 >Array的簡單使用(Boost和STL通用)

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