t _year)
{
id = _id;
stu.name = _name;
stu.year = _year;
}
};
// 获取学生年龄大于20岁并且小于30岁的人
bool GetRange(pair<int, Student::Info> s)
{
if (s.second.year > 20 && s.second.year < 30)
return 1;
return 0;
}
int main(int argc, char* argv[])
{
// 初始化学生数据
Student stu1 = Student(1, "admin", 10);
Student stu2 = Student(2, "guest", 21);
Student stu3 = Student(3, "lyshark", 35);
// 映射Map结构数据,并将上方的数据插入到Map中
map<int, Student::Info> mp;
pair<int, Student::Info> pairSt1(stu1.id, stu1.stu);
mp.insert(pairSt1);
pair<int, Student::Info> pairSt2(stu2.id, stu2.stu);
mp.insert(pairSt2);
pair<int, Student::Info> pairSt3(stu3.id, stu3.stu);
mp.insert(pairSt3);
// 条件统计,统计出年龄大于20岁并且小于30岁的人有多少个= num
int num = 0;
num = count_if(mp.begin(), mp.end(), GetRange);
cout << num << endl;
system("pause");
return 0;
}
7.10 数组查找算法
Binary_search 算法函数,用于在有序序列中查找某个元素。binary_search的用法如下:
template<class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last, const T& value);
其中,first、last
是前向迭代器,表示待查找的有序序列的范围;value
是需要查找的元素的值。调用binary_search
函数后,将会在[first, last]
区间中使用二分查找算法查找value
。如果value
存在于区间[first, last]
中,则函数返回true;否则函数返回false。
该算法就是折半查找法,查找的元素集合必须是一个有序的序列,如下则是一段演示案例;
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
vector<int> var{ 1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10 };
bool ret = binary_search(var.begin(), var.end(), 4);
if (ret)
cout << "found ok" << endl;
else
cout << "not found" << endl;
system("pause");
return 0;
}
7.11 元素不匹配查找
Mismatch 算法函数,用于查找两个序列中第一个不匹配的元素。mismatch函数的用法如下:
template<class InputIterator1, class InputIterator2>
pair<InputIterator1,InputIterator2> mismatch (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2);
其中,first1、last1
是迭代器,表示第一个序列的范围;first2
是迭代器,表示第二个序列的起始位置。调用mismatch
函数后,将会在[first1, last1]
区间和以first2
为起始位置的序列进行元素值的逐一比较,若两个序列中对应元素值都相等,则继续比较下一个元素。一旦出现对应元素不相等时,函数返回一个pair
对,pair
对的第一个元素是距离[first1, last1]
开头最近不匹配的元素的迭代器,pair
对的第二个元素是距离first2
开头最近不匹配的元素的迭代器。
该算法函数比较两个序列,并从中找出首个不匹配元素的位置,如下则是一段演示案例;
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
bool StrEqual(const char* x, const char* y)
{
return strcmp(x, y) == 0 ? 1 : 0;
}
int main(int argc, char* argv[])
{
vector<int> var1{ 2, 0, 0, 6 };
vector<int> var2{ 2, 0, 0, 7 };
// 检测var1与var2中不匹配元素数,并输出
pair<vector<int>::iterator, vector<int>::iterator> result;
result = mismatch(var1.begin(), var1.end(), var2.begin());
if (result.first == var1.end() && result.second == var1.end())
cout << "var1 与var2完全一致" << endl;
else
// var1 和var2不相同,不匹配的数是
cout << "var1 = " << *result.first << " --> var2= " << *result.second << endl;
// ---------------------------------------------------------------------------------
// 针对字符串的不匹配检测
char * str1[] = { "apple", "pear", "banana", "grape" };
char * str2[] = { "apple"