hello~ 很高兴见到大家! 这次带来的是C++中关于map和set这部分的一些知识点,如果对你有所帮助的话,可否留下你宝贵的三连呢? 个 人 主 页: 默|笙


set<int> s = { 5,1,5,3,4,2,6,8,3,9,10,22 };//排序+去重
set<int>::iterator it1 = s.begin();
//正向遍历
while (it1 != s.end())
{
cout << *it1 << " ";
it1++;
}
cout << endl;
//反向遍历
set<int>::reverse_iterator it2 = s.rbegin();
while (it2 != s.rend())
{
cout << *it2 << " ";
it2++;
}
cout << endl;
//范围for
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
return 0;






set<int> s = { 5,1,5,3,4,2,6,8,3,9,10,22 };//排序+去重
set<int>::iterator it1 = s.begin();
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
//删除区间[3,9]的值
auto it3 = s.lower_bound(3);
auto it4 = s.upper_bound(9);
s.erase(it3, it4);
for (auto e : s)
{
cout << e << " ";
}
cout << endl;

3. 对于erase的第二个版本,multiset会删除所有等于val的元素,并返回删除的个数。 4. 对于find,multiset会返回指向它找到的第一个(中序第一个)等于val值的元素的迭代器,没有找到则会返回multiset::end()。 5. 对于count,相比于set,返回的不再只是0或1,可以有更多的值,毕竟multiset支持存储冗余数据。



map<string, string> m = { {"left", "左边"}, {"right", "右边"}, {"insert", "插入"},{ "string", "字符串" } };
auto it1 = m.begin();
//正向迭代
while (it1 != m.end())
{
cout << it1->first << " " << it1->second << endl;
it1++;
}
cout << endl;
auto it2 = m.rbegin();
//反向迭代
while (it2 != m.rend())
{
cout << it2->first << " " << it2->second << endl;
it2++;
}
cout << endl;
//范围for
for (auto e : m)
{
cout << e.first << " " << e.second << endl;
}
cout << endl;


m.insert({"insert1", "1"});//隐式类型转换
m.insert(make_pair("insert2", "2"));//使用make_pair构造
m.insert(pair<string, string>("insert3", "3"));//调用pair构造函数

今天的分享就到此结束啦,如果对读者朋友们有所帮助的话,可否留下宝贵的三连呢~~ 让我们共同努力, 一起走下去!