常用遍历算法:
for_each // 遍历容器 最常用的遍历算法
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printf1(int val) //普通函数
{
cout<<val<<" ";
}
class printf2 //仿函数
{
public:
void operator()(int val)
{
cout<<val<<" ";
}
};
void test()
{
vector<int>v;
for(int i=0; i<10; i++)
{
v.push_back(i);
}
//遍历算法
for_each(v.begin(),v.end(),printf1);
cout<<endl;
for_each(v.begin(),v.end(),printf2());
cout<<endl;
}
int main()
{
test();
return 0;
}
transform // 搬运容器到另一个容器
常用的查找算法:
find: 返回值是个迭代器
#include <iostream>
#include <algorithm>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//查找内置数据类型
void test()
{
vector<int>v;
for(int i=0; i<10; i++)
{
v.push_back(i);
}
//查找容器中是否有7这个元素
vector<int>::iterator it=find(v.begin(),v.end(),7);
if(it == v.end())
{
cout<<"没找到"<<endl;
}
else
{
cout<<"找到"<<*it<<endl;
}
}
//查找自定义类型
class person
{
public:
person(string n,int a)
{
this->name=n;
this->age=a;
}
//重载== 底层的find知道如何对比person数据类型
bool operator==(const person& p)
{
if(this->name==p.name && this->age==p.age)
{
return true;
}
else
{
return false;
}
}
string name;
int age;
};
void test2()
{
vector<person>v;
person p1("aa",1);
person p2("bb",2);
person p3("cc",6);
person p4("dd",3);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
person pp("cc",6);
vector<person>::iterator it =find(v.begin(),v.end(),pp);
if(it == v.end())
{
cout<<"没找到"<<endl;
}
else
{
cout<<"找到"<< it->name<<" "<<it->age<<endl;
}
}
int main()
{
test();
test2();
return 0;
}
find_if
#include <iostream>
#include <algorithm>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//查找算法find_if
//查找内置数据类型
class find0
{
public:
bool operator()(int val)
{
return val>5;
}
};
void test()
{
vector<int>v;
for(int i=0; i<10; i++)
{
v.push_back(i);
}
vector<int>::iterator it= find_if(v.begin(),v.end(),find0());
if(it==v.end())
{
cout<<"没找到"<<endl;
}
else
{
cout<<"找到大于5的数"<<*it<<endl;
}
}
//查找自定义类型
class person
{
public:
person(string n,int a)
{
this->name =n;
this->age=a;
}
string name;
int age;
};
class compare
{
public:
bool operator()(person &p)
{
return p.age>2;
}
};
void test2()
{
vector<person>v;
person p1("aa",1);
person p2("bb",2);
person p3("cc",3);
person p4("dd",4);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
vector<person>::iterator it=find_if(v.begin(),v.end(),compare());
if(it==v.end())
{
cout<<"没找到"<<endl;
}
else
{
cout<<"找到 "<<it->name <<" "<<it->age<<endl;
}
}
int main()
{
test();
test2();
return 0;
}
adjacent_find 查找相邻重复元素
binary_search (容器元素必须有序) 二分查找
count
count_if
利用仿函数