#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
// find算法查找元素 返回查找元素位置
void find1()
{
vector<int >v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector <int >::iterator pos = find(v.begin(), v.end(), 5); // 查找元素为5的元素
if (pos!=v.end())
{
cout << "找到了。。。" << endl;
}
else
{
cout << "未找到。。。" << endl;
}
}
class Person {
public:
Person(string name,int age)
{
m_age = age;
m_name = name;
}
bool operator==(const Person &p)const
{
if (this->m_name == p.m_name&&this->m_age == p.m_age)
return true;
return false;
}
string m_name;
int m_age;
};
// find查找自定义类型
void find2()
{
vector<Person>v;
Person p1("a", 11);
Person p2("b", 22);
Person p3("c", 33);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
vector <Person>::iterator pos = find(v.begin(), v.end(), p2); // 查找元素为p2的元素
if (pos != v.end())
{
cout << "找到了:" << (*pos).m_name << (*pos).m_age << endl;
}
else
{
cout << "未找到。。。" << endl;
}
}
class MyCompare :public binary_function<Person*, Person*, bool > {
public:
bool operator()(const Person * p1,const Person * p2) const
{
if (p1->m_name == p2->m_name && p1->m_age == p2->m_age)
{
return true;
}
return false;
}
};
void find3()
{
vector<Person*>v;
Person p1("a", 11);
Person p2("b", 22);
Person p3("c", 33);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
Person *p = new Person("b", 22);
vector <Person*>::iterator pos = find_if(v.begin(), v.end(), bind2nd(MyCompare(), p)); // 查找元素为p1的元素
if (pos != v.end())
{
cout << "找到了:" << (*pos)->m_name << (*pos)->m_age << endl;
}
else
{
cout << "未找到。。。" << endl;
}
}
// adjacent_find算法查找相邻重复元素, 返回相邻元素的第一个位置的迭代器
void find4()
{
vector<int>v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::iterator pos = adjacent_find(v.begin(), v.end());
if (pos != v.end())
{
cout << "找到了相邻元素" << endl;
}
else
{
cout << "未找到相邻。。" << endl;
}
}
// binary_search算法 二分查找 无序序列中不可用 返回true/false
void find5()
{
vector<int >v;
for (int i=0;i<10;i++)
{
v.push_back(i);
}
bool ret=binary_search(v.begin(), v.end(), 4);
if (ret)
{
cout << "找到find5"<<endl;
}
else
{
cout << "未找到find5"<<endl;
}
}
// count算法 统计元素出现次数 返回元素个数
void find6()
{
vector<int >v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
int num=count(v.begin(),v.end(),4);
cout <<"出现次数:"<< num<<endl;
}
class ThenFour {
public:
bool operator()(int v)
{
return v > 4;
}
};
// count_if算法 按条件统计元素出现次数 返回元素个数
void find7()
{
vector<int >v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
int num = count_if(v.begin(), v.end(), ThenFour());
cout << "出现大于4的次数:" << num << endl;
}
int main()
{
find1();
find2();
find3();
find4();
find5();
find6();
find7();
}
stl::(11) Common search algorithms
Guess you like
Origin blog.csdn.net/qq_40329851/article/details/114423587
Recommended
Ranking