文章目录
- 遍历算法
- 1. for_each()
- 代码工程
- 运行结果
- 2. transform()
- 代码工程
- 运行结果
- 3. find()
- 代码工程
- 运行结果
遍历算法
1. for_each()
有两种方式:
1.普通函数
2.仿函数
代码工程
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>using namespace std;/*普通函数*/
void print01(int val)
{cout << val << " ";
}/*仿函数*/
class print02
{
public:void operator()(int val){cout << val << " ";}
};void test01()
{vector<int>v;for (int i = 0; i < 5; i++){v.push_back(i);}/*普通函数*/for_each(v.begin(), v.end(), print01);cout << endl;/*仿函数*/for_each(v.begin(), v.end(), print02());cout << endl;return;
}int main()
{test01();return 0;
}
运行结果
2. transform()
要注意:需要提前给目标容器开辟空间
代码工程
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>using namespace std;class print
{
public:void operator()(int val){cout << val << " ";}
};class Transform
{
public:int operator()(int val){return val;}
};void test01()
{vector<int>v;for (int i = 0; i < 5; i++){v.push_back(i);}vector<int>vTarget;vTarget.resize(v.size());/*目标容器需要提前开辟空间*/transform(v.begin(), v.end(), vTarget.begin(), Transform());for_each(v.begin(), v.end(), print());cout << endl;for_each(vTarget.begin(), vTarget.end(), print());cout << endl;return;
}int main()
{test01();return 0;
}
运行结果
3. find()
要注意:bool operator==(const Person &p)
参数里要加const修饰
代码工程
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>using namespace std;class Person
{
public:Person(string name, int age){m_name = name;m_age = age;}bool operator==(const Person &p){if (this->m_name == p.m_name && this->m_age == p.m_age){return true;}else{return false;}}string m_name;int m_age;
};
void test01()
{vector<int>v;for (int i = 0; i < 5; i++){v.push_back(i);}/*在v容器中查找5这个元素*/vector<int>::iterator pos = find(v.begin(), v.end(), 4);if (pos == v.end()){cout << "没找到该元素" << endl;}else{cout << "找到该元素,为:" << *pos << endl;}return;
}void test02()/*测试自定义数据类型*/
{Person p1("刘备", 26);Person p2("曹操", 30);Person p3("赵云", 28);Person pp("赵云", 28);vector<Person>v;v.push_back(p1);v.push_back(p2);v.push_back(p3);vector<Person>::iterator pos = find(v.begin(), v.end(), pp);if (pos == v.end()){cout << "没找到该元素" << endl;}else{cout << "找到该元素" << "名字: " << pos->m_name << " 年龄:" << pos->m_age << endl;}return;
}int main()
{test01();cout << endl;test02();return 0;
}