这篇文章介绍一下STL中multiset的基本使用方法。
目录
- set
- 头文件和命名空间
- 常用的成员函数
- 代码使用示例
- 示例执行结果
- 总结
set
使用场景:set能实现很多内容,可能实际想的最多的就是key-value映射的数据类型,按key取值是实际的使用示例,set和map的最大区别在于是否能够有重复。
头文件和命名空间
#include
using namespace std;
常用的成员函数
| 函数名 | 用途 | 功能说明 |
|---|---|---|
| size() | 查询遍历 | 获取元素个数 |
| begin() | 查询遍历 | 获取指向第一个元素的迭代器(正序) |
| end() | 查询遍历 | 获取末尾的迭代器(正序) |
| rbegin() | 查询遍历 | 获取指向第一个元素的迭代器(逆序) |
| rend() | 查询遍历 | 获取末尾的迭代器(逆序) |
| empty() | 查询遍历 | 确认map是否为空 |
| find(x) | 查询遍历 | 查找x,返回相应的迭代器的位置 |
| insert(x) | 插入 | 插入数据x |
| erase(x) | 删除 | 删除指定元素x |
| clear() | 删除 | 删除所有元素 |
代码使用示例
#include#includeusing namespace std;
int check_after_insert(string str,multisets) {
if (s.find(str) != s.end()) {
cout << "Insert Success. " << endl; return 1;
} else {
cout << "Insert Failed." << endl; return 0;
}
}
int main() {
multisets;
cout << "Size of map s : " << s.size() << endl;
s.insert("LiuMiao");
check_after_insert("LiuMiao",s);
s.insert("LiuMiaoCN");
check_after_insert("LiuMiaoCN",s);
s.insert("Michael");
check_after_insert("Michael",s);
s.insert("LiuMiaoCN");
check_after_insert("LiuMiaoCN",s);
cout << "Size of set s : " << s.size() << endl;
multiset::iterator it = s.begin();
cout << "begin(): [" << *it << "]" << endl;
it = s.end();
//cout << "begin(): [" << *it << "]" << endl;
it--;
cout << "begin(): [" << *it << "]" << endl;
for (it=s.begin(); it != s.end(); it++) cout << "[ " << *it << "]" << endl;
multiset::reverse_iterator rit;
for (rit=s.rbegin(); rit != s.rend(); rit++) cout << "[ " << *rit << "]" << endl;
it = s.find("LiuMiao");
if (it != s.end()) {
cout << "Founded: " << "[ " << *it << "]" << endl;
} else {
cout << "LiuMiao: Not Founded. " << endl;
}
it = s.find("LiuMiao");
s.erase(it);
for (rit=s.rbegin(); rit != s.rend(); rit++) cout << "[ " << *rit << "]" << endl;
it = s.find("LiuMiao");
if (it != s.end()) {
cout << "Founded: " << "[ " << *it << "]" << endl;
} else {
cout << "LiuMiao: Not Founded. " << endl;
}
}
示例执行结果
Size of map s : 0 Insert Success. Insert Success. Insert Success. Insert Success. Size of set s : 4 begin(): [LiuMiao] begin(): [Michael] [ LiuMiao] [ LiuMiaoCN] [ LiuMiaoCN] [ Michael] [ Michael] [ LiuMiaoCN] [ LiuMiaoCN] [ LiuMiao] Founded: [ LiuMiao] [ Michael] [ LiuMiaoCN] [ LiuMiaoCN] LiuMiao: Not Founded.
总结
变长支持、泛化类型、常用功能函数内嵌、可以使用其他多种STL的函数、使用简单,结合其他类型进行泛化,使用非常广泛,与set相比主要的特点在于可重复,本文示例代码和set除了将定义从set修改为multiset之外,其余完全不变,使用方法一致。
