非修正序列算法
非修正序列算法不修改他们所作用的容器,例如计算元素个数和查找元素的函数。
函数 |
算法 |
adjacent_find(first, last) |
搜索相邻的重复元素 |
count(first, last, val) |
计数 |
equal(first, last, first2) |
判断是否相等 |
find(first, last, val) |
搜索 |
find_end(first, last, first2, last2) |
搜索某个子序列的最后一次出现地点 |
find_first(first, last, first2, last2) |
搜索某些元素的首次出现地点 |
for_each(first, last, func) |
对 first 到 last 范围内的各个元素执行函数 func 定义的操作 |
mismatch(first, last, first2) |
找出不吻合点 |
search(first, last, first2, last2) |
搜索某个子序列 |
adjacent_find(first, last)
返回一个迭代器,指向第一对同值元素对的第一个元素。函数在迭代器 first 和 last 指明的范围内查找。此函数还有一个谓词版本,其第 3 个实参是一个比较函数。
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
void Test_adjacent_find()
{
multiset<int> int_set;
int_set.insert(7);
int_set.insert(5);
int_set.insert(1);
int_set.insert(5);
int_set.insert(7);
cout << "Set:";
for (int item : int_set) cout << item << endl;
cout << "第一次匹配 ";
multiset<int>::iterator it = adjacent_find(int_set.begin(), int_set.end());
if (it == int_set.end())
{
cout << "没有相邻的重复元素1" << endl;
return;
}
cout << *it++ << ' ' << *it << endl; // it++ 先打印第一个元素,再更新迭代器
cout << "第二次匹配 ";
it = adjacent_find(it, int_set.end());
if (it == int_set.end())
{
cout << "没有相邻的重复元素2" << endl;
return;
}
cout << *it++ << ' ' << *it << endl;
}
Output |
Set:1 5 5 7 7 第一次匹配 5 5 第二次匹配 7 7 |
count(first, last, val)
返回容器中值为 val 的元素个数。函数在迭代器 first 和 last 指明的范围内查找。
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
void Test_count()
{
multiset<int> int_set;
int_set.insert(1);
int_set.insert(5);
int_set.insert(6);
int_set.insert(2);
int_set.insert(5);
int_set.insert(3);
int_set.insert(7);
int_set.insert(5);
cout << "Set:";
for (int item : int_set) cout << item << endl;
int num_count = count(int_set.begin(), int_set.end(), 5);
cout << "元素5数量:" << num_count << endl;
}
Output |
Set:1 2 3 5 5 5 6 7 元素5数量:3 |
for_each(first, last, func)
对 first 到 last 范围内的各个元素执行函数 func 定义的操作。
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
// 输出函数
void Output(int val)
{
cout << val << ' ';
}
void Test_for_each()
{
set<int> int_set;
int_set.insert(2);
int_set.insert(3);
int_set.insert(1);
cout << "Set:";
for_each(int_set.begin(), int_set.end(), Output);
cout << endl;
}
相关参考
微软文档(algorithm)
cppreference(algorithm)