or adjacent_find(InputIterator first, InputIterator last);
其中,first、last
是迭代器,表示待查找的序列的范围。调用adjacent_find
函数后,将会在[first, last]
区间中查找相邻元素的第一个出现位置,并将找到的元素的迭代器作为函数返回值返回。如果未找到相邻元素,则函数将返回last。
该函数用于查找相等或满足条件的相邻的重复的元素,找到了返回第一个出现位置的迭代器,如下则是一段演示案例;
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
bool MyFunction(int x,int y) { return (x - y) % 2 == 0 ? 1 : 0; }
int main(int argc, char* argv[])
{
list<int> ls {1,2,3,4,5,6,6,7,8,9,10};
// 查找链表中邻接相等的元素
list<int>::iterator it = adjacent_find(ls.begin(), ls.end());
if (it != ls.end())
cout << *it << endl;
// 查找基偶性相同的邻接元素
it = adjacent_find(ls.begin(), ls.end(), MyFunction);
if (it != ls.end())
{
cout << *it << endl;
it++;
cout << *it << endl;
}
system("pause");
return 0;
}
7.7 范围查找容器元素
Find_first_of 算法函数,用于查找第一个出现于另一个序列中的指定元素。find_first_of的用法如下:
template<class InputIterator, class ForwardIterator>
InputIterator find_first_of(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2);
其中,first1、last1
是迭代器,表示待查找的序列的范围;first2、last2
是迭代器,表示要查找的元素序列的范围。调用find_first_of
函数后,将会在[first1, last1]
区间中查找第一个与[first2, last2]
中任意一个元素相等的元素,并将找到的元素的迭代器作为函数返回值返回。如果未找到满足条件的元素,则函数将返回last1。
该算法可用于查找位于某个范围之内的元素,如下则是一段演示案例;
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
char * str1 = "hello";
char * str2 = "lyshark This is a test case. Thank you for using it lyshark.";
char * result = find_first_of(str1, str1 + strlen(str1), str2, str2 + strlen(str2));
// 字符串str1的第一个字符,第一次出现在str2中的字符为.
cout << *result << endl;
system("pause");
return 0;
}
7.8 普通元素计数统计
Count 算法函数,用于统计序列中指定值的元素个数。count函数的用法如下:
template<class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type count(InputIterator first, InputIterator last, const T& value);
其中,first、last
是迭代器,表示待计数的序列的范围;value
是需要计数的元素的值。调用count
函数后,将会在[first, last]
区间中统计等于value
的元素个数,并将结果作为函数返回值返回。
该算法用于计算容器中某个给定值得出现次数,如下则是一段演示案例;
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
list<int> ls;
// 批量插入测试数据
for (int x = 0; x < 100; x++)
{
ls.push_back(x % 20);
}
// 统计元素value出现次数,将次数放入num中.
int num = 0; int value = 9;
num = count(ls.begin(), ls.end(), value);
cout << "这个值出现过(次): " << num << endl;
system("pause");
return 0;
}
7.9 条件元素计数统计
Count_if 算法函数,用于统计满足给定条件的元素个数。count_if函数的用法如下:
template<class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last, UnaryPredicate pred);
其中,first、last
是迭代器,表示待计数的序列的范围;pred
是一个一元谓词函数,用于指定计数条件。调用count_if
函数后,将会在[first, last]
区间中统计满足谓词pred
的元素个数,并将结果作为函数返回值返回。
该算法与Count
算法非常类似,区别在于Count_if
可以在统计前增加判断条件,如下则是一段演示案例;
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
struct Student{
struct Info{
char *name; // 学生姓名
int year; // 学生年龄
};
int id; // 学号
Info stu; // 学生Info数据
Student(int _id, char *_name, in