其实里面查找算法用多了就熟悉了,现在来了解一下。
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//常用的查找算法
void test01()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
auto ret = find(v.begin(), v.end(), 5);
if (ret != v.end())
{
cout << "找到了 " << *ret << endl;
}
else
cout << "没有找到" << endl;
}
//查找对象
class Person
{
public:
Person(int age, int id) :age(age), id(id) {}
bool operator==(const Person& p) //里面要加上const
{
return p.age == this->age && p.id == this->id;
}
public:
int age;
int id;
};
void test02()
{
vector<Person> v;
Person p1(10, 11), p2(20, 21), p3(30, 31);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
auto ret = find(v.begin(), v.end(), p2);
if (ret == v.end())
{
cout << "没有找到" << endl;
}
else
cout << "找到了" << endl;
}
//二分查找
bool MySearch(int val)
{
return val > 5;
}
void test03()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
auto ret = binary_search(v.begin(), v.end(), 5);
if (ret)
{
cout << "找到了" << endl;
}
else
cout << "没有找到" << endl;
v.push_back(9);
auto it2 = adjacent_find(v.begin(), v.end());
if (it2 != v.end())
{
cout << "找到相邻重复元素:" <<*it2 << endl;
}
else
cout << "没有找到相邻重复元素" << endl;
//find_if 会根据我们的函数(条件),返回第一个满足条件的迭代器
auto iter_f = find_if(v.begin(), v.end(), MySearch); //要加上回调函数
if (iter_f != v.end())
{
cout << "yes";
}
else
cout << "no";
//count count_if
int num = count(v.begin(), v.end(), 9);
cout << "9出现的次数 :" << num << endl;
num = count_if(v.begin(), v.end(), MySearch);
cout << "统计大于5的元素个数 :" << num << endl;
}
//常用的遍历算法
//transform 将一个容器的元素 搬运 到另一个容器中
class MyPlus
{
public:
int operator()(int val)
{
return val;
}
};
void Print(int val)
{
cout << val<< " ";
}
void test04()
{
vector<int> v;
vector<int> v2;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//v2.reserve(v.size());
v2.resize(v.size()); //开辟空间 ,这里必须用resize(),不能用上面的
//下面就是transform基本的用法
transform(v.begin(), v.end(), v2.begin(), MyPlus());
for_each(v2.begin(), v2.end(), Print);
cout << endl;
}
int main()
{
//test01();
//test02();
//test03();
test04();
system("pause");
return 0;
}