- 针对自定义数据
- 查找,重载==操作符
- 排序,重载<操作符
- 注意源码的返回值,可以用成员函数重载,节省一个参数
- 双向迭代器,不支持begin()+n操作,可以用it++,相等于it=it->next,重载了
- list不能用系统的sort()算法–只支持随机迭代器。有自己的L.sort()
- 指定排序规则L.sort(func)
- 仿函数的本质:类的成员函数重载()操作符,对象()的形式像函数一样调用。
- 类()是匿名函数
- 函数名就是函数指针,可以当作参数传递
待解决问题:类内实现仿函数为什么不行
#include <iostream>
#include<string>
#include<list>
#include<vector>
#include<algorithm>
using namespace std;
class Person
{
public:
Person(string name,int age) {
this->name=name;
this->age=age;
}
public:
string name;
int age;
bool operator ==(const Person&ob)
{
if(this->name==ob.name&&this->age==ob.age)
return true;
return false;
}
bool operator <(const Person&ob)
{
return this->age<ob.age;
}
bool operator()(Person &ob)
{
return this->age>ob.age;
}
};
void printListPerson(list<Person>&L)
{
cout<<"-----------"<<endl;
for(list<Person>::iterator it=L.begin();it!=L.end();it++)
{
cout<<(*it).name<<" "<<(*it).age<<endl;
}
}
void test01()
{
list<Person>L;
L.push_back(Person("的麦西亚",48));
L.push_back(Person("提莫",28));
L.push_back(Person("狗头", 18));
L.push_back(Person("牛头", 19));
printListPerson(L);
Person tmp("狗头",18);
L.remove(tmp);
printListPerson(L);
}
void test02()
{
list<Person> L;
L.push_back(Person("德玛西亚",48));
L.push_back(Person("提莫", 28));
L.push_back(Person("狗头", 18));
L.push_back(Person("牛头", 19));
printListPerson(L);
L.sort();
printListPerson(L);
}
bool myComparePerson(Person&ob1,Person&ob2)
{
return ob1.age>ob2.age;
}
void test03()
{
list<Person> L;
L.push_back(Person("德玛西亚",48));
L.push_back(Person("提莫", 28));
L.push_back(Person("狗头", 18));
L.push_back(Person("牛头", 19));
printListPerson(L);
L.sort(myComparePerson);
printListPerson(L);
}
void PrintVectorPerson(vector<Person>&v)
{
cout<<"-----------"<<endl;
for(vector<Person>::iterator it=v.begin();it!=v.end();it++)
{
cout<<(*it).name<<" "<<(*it).age<<endl;
}
}
class myComparePerson2
{
public:
bool operator()(Person&ob1,Person&ob2)
{
return ob1.age>ob2.age;
}
};
void test04()
{
vector<Person>v;
v.push_back(Person("德玛西亚",48));
v.push_back(Person("提莫", 28));
v.push_back(Person("狗头", 18));
v.push_back(Person("牛头", 19));
PrintVectorPerson(v);
sort(v.begin(),v.end(),myComparePerson2());
PrintVectorPerson(v);
}
class MyAd
{
public:
int operator()(int a,int b)
{
return a+b;
}
int operator ()(int a,int b,int c)
{
return a+b+c;
}
};
void test05()
{
MyAd ob1;
cout<<ob1.operator ()(2,3)<<endl;
cout<<ob1(2,3)<<endl;
cout<<ob1(1,2,3)<<endl;
cout<<MyAd()(2,3)<<endl;
}
void myPrint(vector<int>&v)
{
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
{
cout<<(*it)<<" ";
}
}
void print(int val)
{
cout<<val<<" ";
}
void test06()
{
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
myPrint(v);
for_each(v.begin(),v.end(),print);
for_each(v.begin(),v.end(),[](int val){
cout<<val<<endl;
});
}
int main(int argc, char *argv[])
{
test06();
return 0;
}