更新时间:2022-09-25 19:31:21
按年龄比较Person的大小,直接上代码。
方式一(适用于自定义类型):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#include <iostream> #include <string> #include <map> using namespace std;
struct Person
{ Person(string name, int age)
{
this ->name = name;
this ->age = age;
}
string name;
int age;
bool operator < ( const Person &p1) const
{
return this ->age < p1.age;
}
}; int main()
{ map<Person, string> mm = {
{Person( "Alice" , 34), "girl" },
{Person( "Tom" , 23), "boy" },
{Person( "Joey" , 45), "boy" }
};
for ( const auto &p : mm)
{
cout << p.first.name << " * " << p.first.age << " * " << p.second << endl;
}
return 0;
} |
方式二(适用于不可控的类型):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
#include <iostream> #include <string> #include <map> using namespace std;
struct Person
{ Person(string name, int age)
{
this ->name = name;
this ->age = age;
}
string name;
int age;
}; struct ltPerson
{ bool operator()( const Person &p1, const Person &p2) const
{
return p1.age < p2.age;
}
}; int main()
{ map<Person, string, ltPerson> mm = {
{Person( "Alice" , 34), "girl" },
{Person( "Tom" , 23), "boy" },
{Person( "Joey" , 45), "boy" }
};
for ( const auto &p : mm)
{
cout << p.first.name << " * " << p.first.age << " * " << p.second << endl;
}
return 0;
} |
运行截图:
*** walker ***