C++set或multiset容器

本文介绍C++中set容器的基本操作与pair类型的使用方法,包括元素插入、自定义排序及pair对象创建等。

 

 

 

 

 

 

 

 

 

 

using namespace std;

#include <iostream>
#include <set>

/*
 *
 */

void test() {
    set<int> s;
    pair<set<int>::iterator, bool> ret = s.insert(10);
    if (ret.second) {
        cout << "第一次插入成功" << endl;
    }

    pair<set<int>::iterator, bool> ret2 = s.insert(10);
    if (ret2.second) {
        cout << "第二次插入成功" << endl;
    } else {
        cout << "第二次插入失败" << endl;
    }

    multiset<int> ms;
    ms.insert(10);
    ms.insert(10);

    for (multiset<int>::iterator it = ms.begin(); it != ms.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;


}

int main() {
    test();
    return 0;
}

第一次插入成功
第二次插入失败
10 10 

#include <iostream>
#include <set>

using namespace std;

/*
 *pair对组的使用
 */

void test() {
    //1
    pair<string, int> p("a", 1);
    cout << p.first << "  " << p.second << endl;
    //2
    pair<string, int> p2 = make_pair("b", 2);
    cout << p2.first << "  " << p2.second << endl;
}

int main() {
    test();
    return 0;
}

 

#include <iostream>
#include <set>

using namespace std;

/*
 *set容器排序
 */
class MyCompare {
public:
    bool operator()(int v1, int v2) {
        return v1 > v2;
    }

};

void test() {
    set<int> s1;
    s1.insert(1);
    s1.insert(22);
    s1.insert(4);
    s1.insert(5);
    s1.insert(12);
    //默认是从小到大
    for (set<int>::iterator i = s1.begin(); i != s1.end(); ++i) {
        cout << *i << " ";
    }
    cout << endl;

}

//指定排序规则从大到小
void test2() {
    set<int, MyCompare> s1;
    s1.insert(1);
    s1.insert(22);
    s1.insert(4);
    s1.insert(5);
    s1.insert(12);
    //默认是从小到大
    for (set<int>::iterator i = s1.begin(); i != s1.end(); ++i) {
        cout << *i << " ";
    }
    cout << endl;
}

int main() {
    test();
    test2();
    return 0;
}

自定义数据类型排序

#include <iostream>
#include <set>

using namespace std;

/*
 *set容器排序 自定义类型
 */
class Person {
public:
    Person(string n, int a) {
        name = n;
        age = a;
    }

    string name;
    int age;

};

class MyCompare {
public:
    bool operator()(const Person &p1, const Person &p2) {
        return p1.age > p2.age;
    }
};

void test() {
    //自定义数据类型 都会指定排序规则
    set<Person,MyCompare> s;
    Person p1("a", 1);
    Person p2("b", 2);
    Person p3("c", 3);
    Person p4("d", 4);
    s.insert(p1);
    s.insert(p2);
    s.insert(p3);
    s.insert(p4);
    for (set<Person>::iterator it = s.begin(); it != s.end(); it++) {
        cout << it->name << " " << it->age << endl;
    }

}

int main() {
    test();
    return 0;
}
d 4
c 3
b 2
a 1

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值