标准模板库 (STL) 是 C++ 标准库中一个强大的组件,它提供了各种通用数据结构和算法。STL 旨在提高代码的可重用性、效率和可读性。本文将介绍 C++ 中一些常用的 STL,并提供代码示例。
容器
容器是用于存储和组织数据的对象。STL 中提供了以下几种容器:
- vector:一个动态数组,可以高效地添加和删除元素。
#include <vector>
int main() {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for (int i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
- list:一个双向链表,可以高效地插入和删除元素。
#include <list>
int main() {
std::list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
for (int i : l) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
- set:一个无序集合,其中元素是唯一的。
#include <set>
int main() {
std::set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
for (int i : s) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
- map:一个关联容器,其中键与值相关联。
#include <map>
int main() {
std::map<int, std::string> m;
m[1] = "one";
m[2] = "two";
m[3] = "three";
for (auto it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << " => " << it->second << std::endl;
}
return 0;
}
算法
STL 还提供了各种算法,用于对容器中的元素进行操作。以下是一些常用的算法:
- sort:对容器中的元素进行排序。
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v = {3, 1, 2};
std::sort(v.begin(), v.end());
for (int i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
- find:在容器中查找特定元素。
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v = {3, 1, 2};
std::vector<int>::iterator it = std::find(v.begin(), v.end(), 2);
if (it != v.end()) {
std::cout << "Found 2 at index " << it - v.begin() << std::endl;
} else {
std::cout << "2 not found" << std::endl;
}
return 0;
}
- count:计算容器中特定元素出现的次数。
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v = {3, 1, 2, 2};
int count = std::count(v.begin(), v.end(), 2);
std::cout << "2 appears " << count << " times" << std::endl;
return 0;
}
迭代器
迭代器是用于遍历容器中元素的特殊对象。STL 提供了以下几种迭代器:
- begin:返回容器的第一个元素的迭代器。
- end:返回容器的最后一个元素的迭代器。
- rbegin:返回容器的第一个元素的逆向迭代器。
- rend:返回容器的最后一个元素的逆向迭代器。
代码演示:
// 使用迭代器遍历 vector
for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
结论
STL 是 C++ 中一个强大的工具,它提供了各种通用数据结构和算法。通过使用 STL,开发人员可以提高代码的可重用性、效率和可读性。本文介绍了一些常用的 STL,但还有许多其他有用的组件可供探索。