目录
1.常用遍历算法
for_each
#include<bits/stdc++.h>
using namespace std;
void print(int v)
{
cout << v << ' ';
}
class print2
{
public:
void operator()(int v)
{
cout << v << ' ';
}
};
int main()
{
vector<bool> v;
v.push_back(1);
v.push_back(1);
v.push_back(0);
v.push_back(0);
v.push_back(1);
for_each(v.begin(),v.end(),print);
cout << endl;
//仿函数
for_each(v.begin(),v.end(),print2());
return 0;
}
transform
必须提前开辟空间
#include<bits/stdc++.h>
using namespace std;
class trans
{
public:
int operator()(int v)
{
return v + 200;
}
};
class print
{
public:
void operator()(int v)
{
cout << v << ' ';
}
};
int main()
{
vector<bool> v;
v.push_back(1);
v.push_back(1);
v.push_back(0);
v.push_back(0);
v.push_back(1);
vector<int> v1;
v1.resize(v.size());
transform(v.begin(),v.end(),v1.begin(),trans());
for_each(v1.begin(),v1.end(),print());
}
2.常用查找算法
find
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
v.push_back(4);
v.push_back(5);
v.push_back(2);
v.push_back(8);
v.push_back(1);
vector<int>::iterator it;
it = find(v.begin(),v.end(),8);
if(it != v.end()) cout << "找到了" << endl;
}
自定义数据类型
#include<bits/stdc++.h>
using namespace std;
class person
{
public:
person(string name,int a)
{
this -> name = name;
this -> a = a;
}
bool operator==(const person &p)
{
if(this -> name == p.name && this -> a == p.a)
return true;
else return false;
}
string name;
int a;
};
int main()
{
vector<person> v;
person p1("aa",99);
v.push_back(p1);
vector<person>::iterator it = find(v.begin(),v.end(),p1);
if(it != v.end()) cout << "找到了" << endl;
}
find_if
#include<bits/stdc++.h>
using namespace std;
class dayu5
{
public:
bool operator()(int v)
{
return v > 5;
}
};
int main()
{
vector<int> v;
v.push_back(3);
v.push_back(2);
v.push_back(9);
v.push_back(4);
v.push_back(10);
vector<int>::iterator it = find_if(v.begin(),v.end(),dayu5());
if(it != v.end()) cout << "找到了" << endl;
}
adjacent_find
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
v.push_back(3);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(4);
vector<int>::iterator it = adjacent_find(v.begin(),v.end());
cout << *it << endl;
}
binary_search
必须是有序的序列
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(4);
bool ret = binary_search(v.begin(),v.end(),3);
cout << ret << endl;
return 0;
}
count
统计自定义数据类型数目时,要重载==符号
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(4);
int num = count(v.begin(),v.end(),4);
cout << num << endl;
return 0;
}
count_if
#include<bits/stdc++.h>
using namespace std;
class dayu2
{
public:
bool operator()(int v)
{
return v > 2;
}
};
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(4);
int num = count_if(v.begin(),v.end(),dayu2());
cout << num << endl;
return 0;
}