C++ 提供了多种容器,可以按顺序存储同一类型的元素。
固定大小的容器有 std::array,而 std::vector 则具备动态调整大小的能力。
声明数组或 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
vector 通常需要更多空间,因为它要为后续的增长分配内存。 你不需要指定大小:
#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
注意:你现在还不需要了解模板概念背后的具体机制,后面的教学大纲里会有它自己的概念。
vector 和数组使用相同的函数来访问元素。
你可以使用成员函数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。