生活随笔
收集整理的這篇文章主要介紹了
C++set容器-内置类型指定排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
set容器排序
利用訪函數,可以改變排序規則
一、set存放內置數據類型
代碼如下:
#include <iostream>
using namespace std
;
#include <set>class Mycompare {public:bool operator()(int v1
, int v2
) {return v1
> v2
;}
};
void test01() {set
<int >s1
;s1
.insert(10);s1
.insert(20);s1
.insert(30);s1
.insert(50);s1
.insert(40);for (set
<int >::iterator it
= s1
.begin(); it
!= s1
.end(); it
++) {cout
<< *it
<< " ";}cout
<< endl
;set
<int, Mycompare
>s2
;s2
.insert(10);s2
.insert(20);s2
.insert(30);s2
.insert(50);s2
.insert(40);for (set
<int, Mycompare
>::iterator it
= s2
.begin(); it
!= s2
.end(); it
++) {cout
<< *it
<< " ";}cout
<< endl
;}int main() {test01();return 0;
}
結果:
二、set存放自定義數據類型
代碼如下:
#include <iostream>
using namespace std
;
#include <set>
#include <cstring>
class Person {public:Person(string name
, int age
) {this->m_Name
= name
;this->m_Age
= age
;}string m_Name
;int m_Age
;
};class comparePerson {public:bool operator()(const Person
&p1
, const Person
&p2
) {return p1
.m_Age
> p2
.m_Age
;}
};void test01() {set
<Person
, comparePerson
>s
;Person
p1("劉備", 28);Person
p2("關羽", 26);Person
p3("張飛", 24);Person
p4("馬超", 22);Person
p5("趙云", 21);s
.insert(p1
);s
.insert(p2
);s
.insert(p3
);s
.insert(p4
);s
.insert(p5
);for (set
<Person
, comparePerson
>::iterator it
= s
.begin(); it
!= s
.end(); it
++) {cout
<< "姓名:" << it
->m_Name
<< " " << "年齡:" << it
->m_Age
<< endl
;}
}int main() {test01();return 0;
}
總結:
對于自定義數據類型,set必須指定排序規則才可以插入數據
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的C++set容器-内置类型指定排序的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。