C++ 提供了不同的容器,讓你以有序的方式存放同一種類型的元素。
有固定大小的容器std::array,也有具備動態調整大小能力的std::vector。
當你宣告陣列或向量時,必須指定容器要存放的元素類型。 陣列還需要指定大小。 看看下列範例,了解這兩種容器類型的初始化方式:
#include <array>
#include <string>
// std::array<element_type, size> variable_name {list of elements}
std::array<std::string, 3> indie_rock {"yeah", "yeah", "yeah"};
// indie_rock contains the elements "yeah" three times
向量通常需要更多空間,因為它會配置記憶體以供後續成長。 你不需要指定大小:
#include <vector>
// std::vector<element_type> variable_name {list of elements}
std::vector<int> countdown {3, 2, 1};
// my_vector contains the elements 3, 2 and 1
注意:你目前還不需要了解模板概念背後的確切運作機制,它在課程大綱樹的後段會有專屬的概念。
向量和陣列使用相同的函式來存取元素。
你可以用成員函式front和back取得容器的第一個和最後一個元素。
也可以用at和[]運算子存取特定的元素。
countdown[0];
// => 3
countdown.at(2);
// => 1
countdown[1] = 4;
// countdown now contains 3, 4 and 1
indie_rock.back() = "yeahs";
// indie_rock is now "yeah", "yeah", "yeahs"
注意:如果你選的位置不在容器的範圍內,
[]可能會導致未定義行為。at函式則會拋出例外,長遠來看,這或許能讓你的日子好過一些。
由於vector的大小並非固定,因此可以新增或移除元素。
兩個常見的用途是emplace_back和pop_back。
std::vector<std::string> witches {"Holly", "Alyssa", "Shannen"};
witches.pop_back();
// Shannen is no longer with the witches
witches.emplace_back("Rose");
// Rose has joined the team
你可以用成員函式empty檢查容器是否為空。
如果想得知元素的數量,可以使用size。