doc/notebook/docs/C++/10.algorithm.md

90 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

1. **查找和比较**
- `find`:在范围内查找元素。
- `find_if`:在范围内查找满足指定条件的元素。
- `count`:统计范围内满足条件的元素个数。
- `count_if`:统计范围内满足指定条件的元素个数。
- `equal`:比较两个范围是否相等。
- `lexicographical_compare`:按字典序比较两个范围。
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
// 查找元素
auto it = find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
cout << "Element found: " << *it << endl;
}
// 查找满足条件的元素
auto it2 = find_if(vec.begin(), vec.end(), [](int x) { return x > 3; });
if (it2 != vec.end()) {
cout << "Element > 3 found: " << *it2 << endl;
}
// 统计元素个数
int num = count(vec.begin(), vec.end(), 2);
cout << "Number of 2s: " << num << endl;
// 比较两个范围
vector<int> vec2 = {1, 2, 3};
bool result = equal(vec.begin(), vec.end(), vec2.begin(), vec2.end());
if (result) {
cout << "Vectors are equal" << endl;
} else {
cout << "Vectors are not equal" << endl;
}
return 0;
}
```
2. **排序和操作**
- `sort`:对范围内的元素进行排序。
- `reverse`:反转范围内的元素顺序。
- `copy`:将范围内的元素复制到另一个位置。
- `remove`:移除范围内满足条件的元素(不会改变容器大小)。
- `remove_if`:移除范围内满足指定条件的元素(不会改变容器大小)。
- `transform`:对范围内的元素执行指定操作。
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {5, 3, 1, 4, 2};
// 排序
sort(vec.begin(), vec.end());
// 反转元素顺序
reverse(vec.begin(), vec.end());
// 复制元素到另一个位置
vector<int> vec2(5);
copy(vec.begin(), vec.end(), vec2.begin());
// 移除元素
vec.erase(remove(vec.begin(), vec.end(), 3), vec.end());
// 对元素执行操作
transform(vec.begin(), vec.end(), vec.begin(), [](int x) { return x * 2; });
// 输出元素
for (auto& num : vec) {
cout << num << " ";
}
cout << endl;
return 0;
}
```