第二十三课:C++标准库概述
学习目标:
- 了解C++标准库的基本组成和功能。
- 学习如何使用C++标准库中的容器和算法。
- 掌握基本的容器类型如
vector
,string
,map
和set
。 - 理解算法库中的常用算法,如
sort
,find
,copy
等。
学习内容:
-
C++标准库简介:
C++标准库是一组预定义的类和函数,用于实现常见的程序任务,如输入/输出处理、字符串操作、数学计算等。它由容器库、算法库、迭代器、函数对象和其他组件构成。 -
容器:
容器是用来管理某一类数据的类模板,如序列和关联容器。代码示例:
#include <iostream> #include <vector> #include <map> using namespace std; int main() { // 使用vector vector<int> v = {1, 2, 3, 4, 5}; for (int i : v) { cout << i << ' '; } cout << endl; // 使用map map<string, int> ages; ages["Alice"] = 30; ages["Bob"] = 25; for (const auto& pair : ages) { cout << pair.first << " is " << pair.second << " years old." << endl; } return 0; }
预计输出效果:
1 2 3 4 5 Alice is 30 years old. Bob is 25 years old.
-
算法:
算法是作用于容器的函数模板,它们通过迭代器进行工作。代码示例:
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> v = {5, 3, 1, 4, 2}; sort(v.begin(), v.end()); // 排序 for (int i : v) { cout << i << ' '; } cout << endl; // 查找元素 auto it = find(v.begin(), v.end(), 3); if (it != v.end()) { cout << "Element found: " << *it << endl; } else { cout << "Element not found" << endl; } return 0; }
预计输出效果:
1 2 3 4 5 Element found: 3
-
迭代器:
迭代器是一个对象,它能够遍历容器中的元素。 -
函数对象:
函数对象(也称为仿函数)是一个行为类似函数的对象,它可以是类实例,重载了operator()
。
练习题:
编写一个程序,使用std::vector
容器存储用户输入的五个整数。然后,使用std::sort
算法对它们进行排序,并使用范围for循环打印排序后的结果。最后,使用std::find
算法查找一个特定的整数,并输出是否找到该整数。
答案:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers;
int temp;
cout << "Please enter five integers:" << endl;
for (int i = 0; i < 5; ++i) {
cin >> temp;
numbers.push_back(temp);
}
// 排序
sort(numbers.begin(), numbers.end());
cout << "Sorted numbers:" << endl;
for (int num : numbers) {
cout << num << ' ';
}
cout << endl;
// 查找
int value;
cout << "Enter a number to find: ";
cin >> value;
auto it = find(numbers.begin(), numbers.end(), value);
if (it != numbers.end()) {
cout << "Number found: " << *it << endl;
} else {
cout << "Number not found." << endl;
}
return 0;
}
预计输出效果(示例):
Please enter five integers:
4 2 5 1 3
Sorted numbers:
1 2 3 4 5
Enter a number to find: 3
Number found: 3
在这个课程中,学生将了解到C++标准库的强大功能,学会使用一些基础但非常重要的容器和算法,这些知识对于理解更高级的C++编程概念至关重要。