C++ STL中在set或multiset中插入元素

C++ STL中在set或multiset中插入元素

用法:multisetst;定义了一个multiset类型变量st,st里面可以存放T类型的数据,并且能自动排序。开始st为空

默认排序规则从小到大。

可用st.insert添加元素,st.find查找元素,st.erase删除元素。

set 和 multiset 的大多数函数的用法类似,它们接受类似的参数,返回类型也类似。例如,要在这
两种容器中插入元素,都可使用成员函数 insert(),这个函数接受要插入的值或容器的指定范围:
setInts.insert (-1);
msetInts.insert (setInts.begin (), setInts.end ());
程序清单 19.2 演示了如何在这些容器中插入元素

0: #include <set>
1: #include <iostream>
2: using namespace std;
3:
4: template <typename T>
5: void DisplayContents(const T& container)
6: {
7: for (auto element = container.cbegin();
8: element != container.cend();
9: ++element)
10: cout << *element << ' ';
11:
12: cout << endl;
13: }
14:
15: int main()
16: {
17: set <int> setInts{ 202, 151, -999, -1 };
18: setInts.insert(-1); // duplicate
19: cout << "Contents of the set: " << endl;
20: DisplayContents(setInts);
21:
22: multiset <int> msetInts;
23: msetInts.insert(setInts.begin(), setInts.end());
24: msetInts.insert(-1); // duplicate
25:
26: cout << "Contents of the multiset: " << endl;
27: DisplayContents(msetInts);
28:
29: cout << "Number of instances of '-1' in the multiset are: '";
30: cout << msetInts.count(-1) << "'" << endl;
31:
32: return 0;
33: }

输出:
Contents of the set:
-999 -1 151 202
Contents of the multiset:
-999 -1 -1 151 202
Number of instances of ‘-1’ in the multiset are: ‘2’
分析:
第 4~13 行是通用的模板函数 DisplayContents( ),您在第 17 和 18 章见过,它将 STL 容器的内容
显示到控制台(屏幕)。第 17 行和第 22 行定义了一个 set 对象和一个 multiset 对象,其中前者使用了
C++11 引入的列表初始化语法。第 18 和 24 行尝试在 set 和 multiset 中插入重复的值。第 23 行演示了
如何使用 insert( )将一个 set 的内容插入到一个 multiset 中,这里是将 setInts 的内容插入到 msetInts 中。
从输出可知, multiset 能够存储多个相同的值,而 set 不能。第 30 行演示了成员函数 multiset::count( )
的用法,它返回 multiset 中有多少个元素存储了指定的值。

mulitset::count( )确定 multiset 包含多少个这样的元素,即其值与通过实参传递给这个函
数的值相同。
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值