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;
其中,size
和max_size
只返回數組的大小。而empty
只在數組大小為0時返回false
,在其他時候返回true
。
Boost和STL的區別
STL
中的Array
在高版本的C++中,會支援更多的constexpr
,如果使用在模板中會更加的方便。
為了支援更低版本的C++,Boost
使用了模板偏特化來處理數組大小為0的情況。
Boost
中有一個assign
函數,功能和fill
一樣,但是STL
中沒有。
原部落格地址://www.cnblogs.com/ink19/p/Boost_Array.html