Modern C++ - Ch4.1.1 std::array
Ch4.1, Linear Container - std::array
std::array背後的邏輯與傳統的array相似,都是fixed size的
但為什麼已經有了傳統array,還需要在standary library內新增並使用std::array呢?
明明standary library有std::vector這個更方便的container,為何還需要std::array?
作者給出了兩個解答
- 能夠避免
std::vector對於記憶體控制的缺點 - 相較於傳統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 | std::vector<int> v; |
Benefits of using std::array
相較於傳統的array, std::array不僅對於standard library的配合程度是更好的,它也可以使用iterator去access裡面的element
例如在callstd::sort時
1 | std::array<int, 4> arr = {1,2,3,4}; |