Ch4.1, Linear Container - std::array

reference

std::array背後的邏輯與傳統的array相似,都是fixed size的
但為什麼已經有了傳統array,還需要在standary library內新增並使用std::array呢?
明明standary library有std::vector這個更方便的container,為何還需要std::array?
作者給出了兩個解答

  1. 能夠避免std::vector對於記憶體控制的缺點
  2. 相較於傳統array,std::array可以更好配合其他”modern”的用法

What’s the drawback of std::vector?

std::vector的大小(capacity, the usage of memory)會隨著內容物的多寡而增長
但是,當我們把物品從std::vector中pop出來後,std::vector卻不會自動的去shrink,除非額外去call shrink_to_fit()

1
2
3
4
5
6
7
8
9
10
11
12
std::vector<int> v;
std::cout<<v.size()<<"\t"<<v.capacity()<<endl; //0 4

v.push_back(1);
v.push_back(2);
v.push_back(3);

std::cout<<v.size()<<"\t"<<v.capacity()<<endl; //3 4

v.clear();
std::cout<<v.size()<<"\t"<<v.capacity()<<endl; //0 4
//The capacity of vector doesn't shrink as the vector is being cleared

Benefits of using std::array

相較於傳統的array, std::array不僅對於standard library的配合程度是更好的,它也可以使用iterator去access裡面的element
例如在callstd::sort

1
2
std::array<int, 4> arr = {1,2,3,4};
std::sort(arr.begin(), arr.end());