// ============================================================================ // p1c09_03_06 — 3.7.2.5 set查找操作 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; #include // --- 原文片段 [58954488:5] 3.7.2.5 set查找操作 --- //插入操作返回值 void test01(){ set s; pair::iterator,bool> ret = s.insert(10); if (ret.second){ cout << "插入成功:" << *ret.first << endl; } else{ cout << "插入失败:" << *ret.first << endl; } ret = s.insert(10); if(ret.second){ cout << "插入成功:" << *ret.first << endl; } else{ cout << "插入失败:" << *ret.first << endl; } } struct MyCompare02{ bool operator()(int v1, int v2) const { return v1 > v2; } }; //set从大到小 void test02(){ srand((unsigned int)time(NULL)); //我们发现set容器的第二个模板参数可以设置排序规则,默认规则是less<_Kty> set s; for (int i = 0; i < 10;i++){ s.insert(rand() % 100); } for (set::iterator it = s.begin(); it != s.end(); it ++){ cout << *it << " "; } cout << endl; } //set容器中存放对象 class Person{ public: Person(string name,int age){ this->mName = name; this->mAge = age; } public: string mName; int mAge; }; struct MyCompare03{ bool operator()(const Person& p1, const Person& p2) const { return p1.mAge > p2.mAge; } }; void test03(){ set s; Person p1("aaa", 20); Person p2("bbb", 30); Person p3("ccc", 40); Person p4("ddd", 50); s.insert(p1); s.insert(p2); s.insert(p3); s.insert(p4); for (set::iterator it = s.begin(); it != s.end(); it++){ cout << "Name:" << it->mName << " Age:" << it->mAge << endl; } } // --- main --- int main() { test01(); test02(); test03(); return 0; }