基本概念
- 所有元素在插入的时候自动被排序
- 都属于关联式容器,底层结构使用二叉树实现
- 头文件<set>包括set和multiset
set和multiset的区别:
- set不允许容器中有重复的元素
- multiset允许
构造与赋值
构造:
- set<T> st; //默认构造函数:
- set(const set &st); //拷贝构造函数
赋值:
- set& operator=(const set &st); //重载等号操作符
#include <iostream>
#include <set>
using namespace std;
void printSet(const set<int>&s)
{
for (set<int>::iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << " " ;
}
cout << endl;
}
int main()
{
set<int>s1;
s1.insert(10);
s1.insert(60);
s1.insert(20);
s1.insert(90);
s1.insert(60);
printSet(s1); //10 20 60 90(排序且不重复)
set<int>s2(s1);
set<int>s3;
s3 = s2;
cout << s3.size() << endl;
printSet(s3); // 10 20 60 90
cout << sizeof(int) << endl; //4
cout << sizeof(s3) << endl; //12(32位),24(64位)
system("pause");
return 0;
}
![]()
这里很奇怪,有大佬知道的话讲一下。 int类型,s3中四个数据,但是只有12字节;
大小与交换
- size(); //返回容器中元素的数目
- empty(); //判断容器是否为空
- swap(st); //交换两个集合容器
插入与删除
- insert(elem); //在容器中插入元素。
- clear(); //清除所有元素
- erase(pos); //删除pos迭代器所指的元素,返回下一个元素的迭代器。
- erase(beg, end); //删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。
- erase(elem); //删除容器中值为elem的元素。
查找和统计
- find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
- count(key); //统计key的元素个数
pair对组创建
- pair<type, type> p ( value1, value2 );
- pair<type, type> p = make_pair( value1, value2 );
set容器排序
//指定排序规则
#include <iostream>
#include <set>
using namespace std;
void printSet(const set<int>&s)
{
for (set<int>::iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
class MyCompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
int main()
{
set<int>s1;
s1.insert(10);
s1.insert(30);
s1.insert(20);
s1.insert(50);
s1.insert(40);
printSet(s1);//默认从小到大
//指定排序规则
set<int,MyCompare>s2;
s2.insert(10);
s2.insert(30);
s2.insert(20);
s2.insert(50);
s2.insert(40);
for (set<int,MyCompare>::iterator it = s2.begin(); it != s2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
system("pause");
return 0;
}
//自定义数据类型
#include <iostream>
#include <set>
#include <string>
using namespace std;
class person
{
public:
person(string name, int age) :m_name(name),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;
}
};
int main()
{
set<person, compareperson>s1;
person p1("张三", 10);
person p2("李四", 20);
person p3("王五", 30);
person p4("赵六", 40);
s1.insert(p1);
s1.insert(p2);
s1.insert(p3);
s1.insert(p4);
for (set<person, compareperson>::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << (*it).m_name << " " << (*it).m_age << endl;
}
//指定排序规则
system("pause");
return 0;
}
本文详细介绍了C++标准库中的set容器,包括其自动排序特性、set和multiset的区别,以及如何构造、赋值和进行插入、删除操作。重点讲解了自定义排序规则和使用set处理自定义数据类型的实例。
510

被折叠的 条评论
为什么被折叠?



