C++常用遍历算法—for_each、transform
1、for_each—遍历容器
1.1 内置数据类型
void print1(int num)
{
cout << "这个数字是:" << num << endl;
}
void test1()
{
vector<int> numList;
for (int i = 0; i < 10; i++)
{
numList.push_back(i);
}
for_each(numList.begin(), numList.end(), print1);
}
1.2 自定义数据类型
class Person
{
public:
string name;
int age;
Person(string name, int age)
{
this->name = name;
this->age = age;
}
Person() {}
};
void printPerson(Person &p)
{
cout << p.name << "今年" << p.age << "岁了!" << endl;
}
void test2()
{
Person p1("ncs", 26);
Person p2("nbl", 9);
Person p3("zes", 51);
vector<Person> pList;
pList.push_back(p1);
pList.push_back(p2);
pList.push_back(p3);
for_each(pList.begin(), pList.end(), printPerson);
}
2、transform—搬运一个容器的内容到另一个容器
2.1 自定义数据类型
int re(int num)
{
return num + 10000;
}
void test3()
{
vector<int> numList;
for (int i = 0; i < 10; i++)
{
numList.push_back(i);
}
vector<int>vTarget;
for (int i = 0; i < 10; i++)
{
vTarget.push_back(i);
}
for_each(vTarget.begin(), vTarget.end(), print1);
vTarget.resize(vTarget.size() + numList.size());
transform(numList.begin(), numList.end(), vTarget.begin()+numList.size(), re);
cout << "++++++++++++++++++++++\n";
for_each(vTarget.begin(), vTarget.end(), print1);
}
2.2 自定义数据类型
Person ageAdd(Person& p)
{
p.age = p.age + 30;
return p;
}
void test4()
{
Person p1("ncs", 26);
Person p2("nbl", 9);
Person p3("zes", 51);
vector<Person> pList;
pList.push_back(p1);
pList.push_back(p2);
pList.push_back(p3);
vector<Person> pList1;
pList1.push_back(p1);
pList1.push_back(p2);
pList1.push_back(p3);
for_each(pList.begin(), pList.end(), printPerson);
pList.resize(pList.size() + pList1.size());
transform(pList1.begin(), pList1.end(), pList.begin() + pList1.size(), ageAdd);
cout << "++++++++++++++++++++++\n";
for_each(pList.begin(), pList.end(), printPerson);
}