001 第一部分 不会修改字符序列的操作
继续上一篇文章:
adjacent_find 返回指向第一个[大于|小于|等于]后面第二个元素的迭代器 具体看传入的条件函数的编写方式
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool myfunction (int i, int j) {
return (i==j); // 返回第一个在连续的序列中等于后面的数的数的迭代器
// 如 1 2 3 3 4 5 -> 返回指向3的迭代器
}
bool myfunction1 (int i, int j) {
return (i>j); // 返回第一个在连续的序列中比后面的数大的数的迭代器
// 如 1 2 3 4 2 5 -> 返回指向4的迭代器
}
bool myfunction2 (int i, int j) {
return (i<j); // 返回第一个在连续的序列中比后面的数小的数的迭代器
// 如 1 2 3 3 4 5 -> 返回指向1的迭代器
}
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v (myints,myints+8);
vector<int>::iterator it;
// 使用默认的方式进行查找
it = adjacent_find (v.begin(), v.end());
if (it!=v.end())
cout << "第1个连续重复的元素是: " << *it << endl;
// 使用条件函数进行查找
it = adjacent_find (++it, v.end(), myfunction);
if (it!=v.end())
cout << "第2个连续重复的元素是: " << *it << endl;
/* 【打印结果】
第1个连续重复的元素是: 30
第2个连续重复的元素是: 10
*/
return 0;
}
count 返回目标元素在指定序列中出现了多少次
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
int mycount;
// counting elements in array:
int myints[] = {10,20,30,30,20,10,10,20}; // 8 elements
mycount = (int) count (myints, myints+8, 10);
cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
vector<int> myvector (myints, myints+8);
mycount = (int) count (myvector.begin(), myvector.end(), 20);
cout << "20 appears " << mycount << " times.\n";
return 0;
/* 【打印结果】
10 appears 3 times. // 数字10出现了3次
20 appears 3 times. // 数字20出现了3次
*/
}
count_if 返回满足条件的元素在指定序列中出现了多少次
条件定义在一个函数中,此函数可以自主实现:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool IsOdd(int i) {
return ((i % 2) == 1);
}
int main() { // 找出[v.begin(), v.end())范围内奇数的个数
int cnt;
vector<int> v;
for (int i = 1; i < 10; i++)
v.push_back(i); // v: 1 2 3 4 5 6 7 8 9
cnt = (int) count_if(v.begin(), v.end(), IsOdd);
cout << "v contains " << cnt << " odd values.\n"; // v contains 5 odd values.
return 0;
}
mismatch 找出两个序列第一个对应不匹配的元素
返回一个pair对象,first存储第一个序列元素的迭代器,second存储第二个序列元素的迭代器
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool rule (int i, int j) {
return (i==j);
}
int main () {
vector<int> v;
for (int i=1; i<6; i++)
v.push_back (i*10); // v: 10 20 30 40 50
int arr[] = {10,20,80,320,1024}; // arr: 10 20 80 320 1024
pair<vector<int>::iterator,int*> mypair;
// *******************************************************************************
mypair = mismatch (v.begin(), v.end(), arr);
cout << "First mismatching elements: " << *mypair.first;
cout << " and " << *mypair.second << endl;;
// -> Result: First mismatching elements: 30 and 80
mypair.first++; mypair.second++;
// *******************************************************************************
mypair = mismatch (mypair.first, v.end(), mypair.second, rule);
cout << "Second mismatching elements: " << *mypair.first;
cout << " and " << *mypair.second << endl;;
// -> Result: Second mismatching elements: 40 and 320
return 0;
}