一、遍历算法
1. for_each(iterator beg, iterator end, _func);
遍历容器。
2. transform(iterator beg1, iterator end1, iterator beg2, _func)
搬运容器,目标容器需要提前开辟空间。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Print
{
public:
void operator()(int val) {
cout << val << " ";
}
};
void test01() {
vector<int> vec = {
0,1,2,3,4,5,6,7,8,9 };
for_each(vec.begin(), vec.end(), Print());
cout << endl;
}
class Transform
{
public:
int operator()(int val) {
return val;
}
};
void test02()
{
vector<int> vec = {
0,1,2,3,4,5,6,7,8,9 };
// 目标容器
vector<int> vTarget;
// 目标容器需要提前开辟空间
vTarget.resize(vec.size());
transform(vec.begin(), vec.end(), vTarget.begin(), Transform());
for_each(vTarget.begin(), vTarget.end(), Print());
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
二、查找算法
1. find(iterator beg, iterator end, value);
按值查找元素,找到返回指定位置的迭代器,找不到返回尾后迭代器。 查找自定义数据类型时,确保该类型定义了==运算符。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// 查找内置数据类型
void test01()
{
vector<int> vec = {
0,1,2,3,4,5,6,7,8,9 };
// 查找容器中是否有5这个元素
vector<int>::iterator it = find(vec.begin(), vec.end(), 5);
if (it == vec.end()) {
cout << "没有找到!" << endl;
}
else {
cout << "找到!" << endl;
}
}
// 查找自定义数据类型
class Person {
public:
Person(string name, int age) {
this->m_Name = name;
this->m_Age = age;
}
// ==运算符
bool operator==(const Person& p) {
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age) {
return true;
}
return false;
}
public:
string m_Name;
int m_Age;
};
void test02()
{
vector<Person> vec;
vec.emplace_back("aaa", 10);
vec.emplace_back("bbb", 20);
vec.emplace_back("ccc", 30);
vec.emplace_back("ddd", 40);
vector<Person>::iterator it = find(vec.begin(), vec.end(), Person("aaa", 10));
if (it == vec.end()) {
cout << "没有找到!" << endl;
}
else {
cout << "找到!" << endl;
}
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
2. find_if(iterator beg, iterator end, _Pred);
按值查找元素,找到返回指定位置的迭代器,找不到返回尾后迭代器。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// 查找内置数据类型
class GreaterFive
{
public:
bool operator()(int val) {
return val > 5;
}
};
void test01()
{
vector<int> vec = {
0,1,2,3,4,5,6,7,8,9 };
vector<int>::iterator it = find_if(vec.begin(), vec.end(), GreaterFive());
if (it == vec.end()) {
cout << "没有找到!" << endl;
}
else {
cout << "找到!" << endl;
}
}
// 查找自定义数据类型
class Person {
public:
Person(string name, int age) {
this->m_Name = name;
this->m_Age = age;
}
public:
string m_Name;
int m_Age;
}