第二十四课:理解STL(标准模板库)
学习目标:
- 掌握STL的基本概念和组成。
- 熟悉STL容器、迭代器、算法的使用和特点。
- 能够运用STL解决实际编程问题。
学习内容:
-
STL简介:
- STL是C++标准库的一部分,它包含了一系列模板类和函数,用以提供常见的数据结构和算法。STL的设计目标是提高软件的复用性和效率。
-
容器(Containers):
- 容器是用来存储数据的对象,STL提供了多种不同类型的容器,每种容器都有其特有的性能和使用场景。
常用容器:
vector
: 动态数组,支持快速随机访问。list
: 双向链表,支持快速插入和删除。map
: 基于红黑树的关联容器,存储键值对。
容器使用示例(
vector
):#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec; // 创建一个空的vector vec.push_back(10); // 添加元素 vec.push_back(20); // 再次添加元素 cout << "Vector elements: "; for (size_t i = 0; i < vec.size(); ++i) { cout << vec[i] << " "; // 通过索引访问元素 } cout << endl; return 0; }
预计输出效果:
Vector elements: 10 20
-
迭代器(Iterators):
- 迭代器是一种访问容器内元素的对象,类似于指针。根据容器的不同,迭代器可能支持不同的操作。
迭代器使用示例:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec = {1, 2, 3, 4, 5}; cout << "Vector elements using iterators: "; for (auto it = vec.begin(); it != vec.end(); ++it) { cout << *it << " "; // 解引用迭代器访问元素 } cout << endl; return 0; }
预计输出效果:
Vector elements using iterators: 1 2 3 4 5
-
算法(Algorithms):
- STL算法是一组模板函数,用来执行诸如查找、排序、计算等操作。
算法使用示例:
#include <iostream> #include <vector> #include <algorithm> // 算法头文件 using namespace std; int main() { vector<int> vec = {4, 2, 5, 1, 3}; sort(vec.begin(), vec.end()); // 排序算法 cout << "Sorted Vector: "; for (auto num : vec) { cout << num << " "; // 范围for循环 } cout << endl; auto it = find(vec.begin(), vec.end(), 3); // 查找算法 if (it != vec.end()) { cout << "Element found in vector: " << *it << endl; } return 0; }
预计输出效果:
Sorted Vector: 1 2 3 4 5 Element found in vector: 3
练习题:
编写一个程序,使用std::map
容器来建立一个简单的电话簿,其中包含姓名和电话号码。然后通过姓名来查找对应的电话号码,找到后打印出来。
答案:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, string> phoneBook;
phoneBook["John Doe"] = "555-1234";
phoneBook["Jane Smith"] = "555-5678";
phoneBook["Bob Stone"] = "555-7890";
string name;
cout << "Enter a name to find the corresponding phone number: ";
getline(cin, name); // 读取带空格的名字
auto it = phoneBook.find(name);
if (it != phoneBook.end()) {
cout << "The phone number of " << name << " is " << it->second << endl;
} else {
cout << "Name not found in phone book." << endl;
}
return 0;
}
预计输出效果(示例):
Enter a name to find the corresponding phone number: John Doe
The phone number of John Doe is 555-1234
在本课中,我们学习了STL的基础知识,了解了如何使用STL的容器、迭代器和算法。这些工具在C++编程中非常有用,能够帮助我们更加高效地管理数据和处理复杂的数据结构。