C++ 列表
最后修改于 2022 年 9 月 7 日
在本文中,我们将展示如何在 C++ 中使用列表容器。
列表是一个保存一系列元素的容器。元素具有特定的类型。列表允许在序列中的任何位置高效地插入和删除元素。
列表没有随机访问运算符;也就是说,无法通过索引运算符 []
从列表中获取值。(向量可用于元素的随机访问。)
C++ 列表大小
列表的大小由 size
确定。
main.cpp
#include <iostream> #include <list> using std::cout; using std::list; int main() { list<int> vals({1, 2, 3, 4, 5, 6, 7}); cout << "The list has " << vals.size() << " elements\n"; }
我们初始化一个整数列表并打印其大小。
list<int> vals({1, 2, 3, 4, 5, 6, 7});
我们使用列表初始化器创建一个整数值列表。列表的类型在 <>
括号之间指定。
cout << "The list has " << vals.size() << " elements\n";
我们打印一条消息,说明列表中有多少个元素。
$ ./main The list has 7 elements
C++ 列表插入元素
以下示例插入新值。
main.cpp
#include <iostream> #include <list> using std::cout; using std::endl; using std::list; using std::string; int main() { list<string> words = {"sky", "car", "cup", "ocean", "war"}; list<string>::iterator it = words.begin(); words.insert(it, "falcon"); words.push_back("world"); words.push_front("water"); for (auto word : words) { cout << word << endl; } }
我们有一系列单词。
list<string>::iterator it = words.begin(); words.insert(it, "falcon");
我们创建一个指向列表开头的迭代器。我们将一个新元素插入到那里。
words.push_back("world"); words.push_front("water");
我们使用 push_back
在末尾添加一个新元素,并使用 push_front
在开头添加一个新元素。
$ ./main water falcon sky car cup ocean war world
C++ 列表删除元素
以下示例删除列表元素。
main.cpp
#include <iostream> #include <list> using std::cout; using std::endl; using std::list; using std::string; int main() { list<string> words = {"sky", "car", "cup", "ocean", "war"}; words.remove("war"); for (auto word : words) { cout << word << endl; } words.clear(); cout << words.size() << endl; }
我们使用 remove
和 clear
删除元素。
words.remove("war");
我们使用 remove
删除指定的元素。
words.clear();
所有元素都使用 clear
删除。
$ ./main sky car cup ocean 0
C++ 循环列表
以下示例循环遍历列表。
classic_for.cpp
#include <iostream> #include <list> using std::cout; using std::endl; using std::list; int main() { list<int> vals = {1, 2, 3, 4, 5, 6, 7}; for (auto it = vals.cbegin(); it != vals.cend(); ++it) { std::cout << *it << endl; } for (auto val : vals) { cout << val << endl; } }
我们使用类 for 循环和 foreach 循环遍历整数列表。
for (auto it = vals.cbegin(); it != vals.cend(); ++it) { std::cout << *it << endl; }
列表使用经典 for 循环进行迭代。cbegin
返回一个指向容器中第一个元素的常量迭代器。cend
返回一个指向容器末尾之后元素的常量迭代器。
for (auto val : vals) { cout << val << endl; }
foreach 循环是遍历容器的简便语法。
$ ./main 1 2 3 4 5 6 7 1 2 3 4 5 6 7
C++ 列表 remove_if
remove_if
函数删除所有满足给定谓词的元素。
main.cpp
#include <iostream> #include <string> #include <list> using std::cout; using std::endl; using std::list; using std::string; int main() { list<string> words = {"sky", "car", "cup", "ocean", "war"}; words.remove_if([](const string& e) { return (e.starts_with("w")); }); for (auto word : words) { cout << word << endl; } }
在示例中,我们从列表中删除所有以 "w" 开头的单词。
$ clang++ main.cpp -o main -std=c++20 $ ./main sky car cup ocean
在本文中,我们使用了 C++ 中的列表容器。