





set<int> se;
se.insert(2);
se.insert(2);
se.insert(5);
for (auto& e : se)
{
cout << e << " ";
}
cout << endl;特点:
// 使用greater仿函数实现降序
set<int, greater<int>> se;
se.insert(2);
se.insert(2);
se.insert(5);
// 自定义仿函数
template<class T>
struct Greater
{
bool operator()(const T& a, const T& b) const
{
return a > b;
}
};
set<int, Greater<int>> se;set<int> se;
se.insert({ 2,8,3,9,2 });本质是遍历初始化列表再插入数据,同样会自动去重。
删除最小值:
set<int> se;
se.insert({ 2,8,3,9,2 });
se.erase(se.begin()); // 中序遍历,begin迭代器指向最小值删除指定值:
set<int> se;
se.insert({ 2,8,3,9,2 });
int num = se.erase(3);
int num2 = se.erase(10);
cout << num << endl; // 输出:1
cout << num2 << endl; // 输出:0
set<int> se;
se.insert({ 2,8,3,9,2 });
auto it = find(se.begin(), se.end(), 9); // 库里的find,复杂度O(n)
auto it2 = se.find(9); // set的find接口,复杂度O(log n)// 返回值的个数(在set中为0或1,为了和multiset对应)
if (se.count(3))
{
cout << "有3" << endl;
}
// 对比find方法
auto sit = se.find(3);
if(sit != se.end())
{
cout << "有3" << endl;
}auto low_it = se.lower_bound(60);
auto up_it = se.upper_bound(60);
cout << *low_it << " " << *up_it << endl;
3. Multiset
允许值冗余的set
multiset<int> mset = { 2,4,4,3,4,6 };
auto it = mset.find(4); // 找到中序遍历的第一个4
while (it != mset.end() && *it == 4)
{
cout << *it;
++it;
}
// 这样,就可以通过遍历,把所有元素找到mset.erase(4); // 删除所有值为4的元素
// erase也可以传迭代器,并返回新的迭代器总体框架与set类似,但是支持[]重载修改val。
pair<int, int> p = { 1,1 };
cout << p.first << ":" << p.second;
// 简易实现
template<class T1, class T2>
struct pair
{
pair()
:first(T1())
, second(T2())
{ }
pair(T1& _first, T2& _second)
:first(_first)
,second(_second)
{ }
T1 first;
T2 second;
};Map有两个元素,使用的就是pair类型。
pair<string, string> k1("a", "A");
map<string, string> ma = {
k1, // 1. 构造pair有名对象插入k1
pair<string, string>("b", "B"), // 2. 匿名对象
make_pair("c", "C"), // 3. make_pair函数返回pair类型
{"d", "D"} // 4. 初始化列表
};ma.insert({ "a", "B" }); // 依旧是原来的,不会更新
4.5 遍历方法
范围for循环:
for (auto& e : ma)
{
cout << e.first << ":" << e.second << endl;
}迭代器遍历:
auto it = ma.begin();
while(it != ma.end())
{
cout << it->first << ":" << it->second << endl;
it++;
}
// 本质:
while(it != ma.end())
{
cout << it.operator->()->first << ":" << it.operator->()->second << endl;
it++;
}
// 取出pair的指针,再指向first// ma.begin()->first = "a"; // 错误,key不可修改
ma.begin()->second = "a"; // 正确,value可以修改map<int, int> ma2;
ma2[2]++; // []有三重含义:插入、查找、修改[]运算符的功能:
可以充当insert的功能。
pair<map<string,string>::iterator, int> r1 = ma.insert({ "a","B" });
pair<map<string, string>::iterator, int> r2 = ma.insert({ "e","E" });
cout << r1.second << ":" << r1.first->first << endl; // 失败:0:a
cout << r2.second << ":" << r2.first->first << endl; // 成功:1:e
注意,这个pair和插入的pair不是同一个。
与map的主要区别:
mmp.erase("a"); 将删除所有key为"a"的pair