C++标准模板库(STL)是C++编程中非常重要的组成部分。它提供了各种容器、迭代器和算法,可以大大提高代码的重用性和开发效率。在本博客中,我们将讨论STL库的使用,并展示一些C++内容丰富的示例。
容器
STL库提供了多种容器,每种容器都有不同的用途和特性。
vector
vector是动态数组,可以在运行时动态调整大小。它的使用方法与普通数组类似,但更加灵活。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec; // 创建一个空的vector
vec.push_back(10); // 在末尾插入元素
vec.push_back(20);
vec.push_back(30);
cout << "Size: " << vec.size() << endl; // 输出vector的大小
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " "; // 遍历并输出vector中的元素
}
cout << endl;
return 0;
}
输出:
Size: 3
10 20 30
list
list是双向链表,可以在任意位置插入和删除元素。它的使用方法与vector类似,但在某些情况下更加高效。
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> myList;
myList.push_back(10);
myList.push_back(20);
myList.push_back(30);
myList.push_front(5); // 在链表头部插入元素
for (int num : myList) {
cout << num << " ";
}
cout << endl;
myList.remove(20); // 删除链表中的元素
for (int num : myList) {
cout << num << " ";
}
cout << endl;
return 0;
}
输出:
5 10 20 30
5 10 30
map
map是一种关联容器,存储键值对。每个键都是唯一的,可以通过键值快速访问和修改相关的值。
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> myMap;
myMap["Alice"] = 20;
myMap["Bob"] = 25;
myMap.insert(make_pair("Charlie", 30));
cout << "Alice's age: " << myMap["Alice"] << endl;
for (auto it = myMap.begin(); it != myMap.end(); it++) {
cout << it->first << " is " << it->second << " years old." << endl;
}
return 0;
}
输出:
Alice's age: 20
Alice is 20 years old.
Bob is 25 years old.
Charlie is 30 years old.
迭代器
STL库提供了迭代器,用于遍历容器中的元素。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {10, 20, 30, 40, 50};
// 使用迭代器访问容器元素
vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); it++) {
cout << *it << " ";
}
cout << endl;
// 使用迭代器修改容器元素
for (it = vec.begin(); it != vec.end(); it++) {
*it *= 2;
}
// 使用范围-based for循环访问容器元素
for (int num : vec) {
cout << num << " ";
}
cout << endl;
return 0;
}
输出:
10 20 30 40 50
20 40 60 80 100
算法
STL库提供了丰富的算法,可以对容器进行排序、查找等操作。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isOdd(int num) {
return num % 2 != 0;
}
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
// 使用算法对容器进行排序
sort(vec.begin(), vec.end());
// 使用算法查找容器中的元素
auto it = find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
cout << "Element found: " << *it << endl;
} else {
cout << "Element not found." << endl;
}
// 使用自定义的谓词函数进行筛选
vector<int> result;
copy_if(vec.begin(), vec.end(), back_inserter(result), isOdd);
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}
输出:
Element found: 3
1 3 5
总结
STL库是C++编程中不可或缺的一部分。本博客介绍了STL库中的容器、迭代器和算法,并提供了一些示例代码。掌握STL库的使用,将能够更加高效地开发C++程序,并提高代码的重用性和可读性。
本文来自极简博客,作者:编程狂想曲,转载请注明原文链接:C++ STL库使用