非修正序列算法
非修正序列算法不修改他們所作用的容器,例如計算元素個數(shù)和查找元素的函數(shù)。
函數(shù) | 算法 |
---|---|
adjacent_find(first, last) | 搜索相鄰的重復(fù)元素 |
count(first, last, val) | 計數(shù) |
equal(first, last, first2) | 判斷是否相等 |
find(first, last, val) | 搜索 |
find_end(first, last, first2, last2) | 搜索某個子序列的最后一次出現(xiàn)地點 |
find_first(first, last, first2, last2) | 搜索某些元素的首次出現(xiàn)地點 |
for_each(first, last, func) | 對 first 到 last 范圍內(nèi)的各個元素執(zhí)行函數(shù) func 定義的操作 |
mismatch(first, last, first2) | 找出不吻合點 |
search(first, last, first2, last2) | 搜索某個子序列 |
adjacent_find(first, last)
返回一個迭代器,指向第一對同值元素對的第一個元素。函數(shù)在迭代器 first 和 last 指明的范圍內(nèi)查找。此函數(shù)還有一個謂詞版本摄杂,其第 3 個實參是一個比較函數(shù)。
#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 << "沒有相鄰的重復(fù)元素1" << endl;
return;
}
cout << *it++ << ' ' << *it << endl; // it++ 先打印第一個元素循榆,再更新迭代器
cout << "第二次匹配 ";
it = adjacent_find(it, int_set.end());
if (it == int_set.end())
{
cout << "沒有相鄰的重復(fù)元素2" << endl;
return;
}
cout << *it++ << ' ' << *it << endl;
}
Output |
---|
Set:1 5 5 7 7 第一次匹配 5 5 第二次匹配 7 7 |
count(first, last, val)
返回容器中值為 val 的元素個數(shù)析恢。函數(shù)在迭代器 first 和 last 指明的范圍內(nèi)查找。
#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數(shù)量:" << num_count << endl;
}
Output |
---|
Set:1 2 3 5 5 5 6 7 元素5數(shù)量:3 |
for_each(first, last, func)
對 first 到 last 范圍內(nèi)的各個元素執(zhí)行函數(shù) func 定義的操作秧饮。
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
// 輸出函數(shù)
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;
}
Output |
---|
Set:1 2 3 |