一、set

在了解关联容器set之前,让我们先来看看下面这个例子,并猜测该例子输出什么:

// stl/set1.cpp

   #include <iostream>
#include <set> int main()
{
//type of the collection
typedef std::set<int> IntSet; IntSet coll; //set container for int values /* insert elements from 1 to 6 in arbitray order
*- value 1 gets inserted twice
*/
coll.insert();
coll.insert();
coll.insert();
coll.insert();
coll.insert();
coll.insert();
coll.insert(); /* print all elements
*- iterate over all elements
*/
IntSet::const_iterator pos;
for (pos = coll.begin(); pos != coll.end(); ++pos) {
std::cout << *pos << ' ';
}
std::cout << std::endl;
}

其中,输出的结果为:1 2 3 4 5 6

下面,我们根据该输出结果对关联容器set做一个分析:

1. set元素的唯一性;

2. set默认按照从小到大排序;This type uses the default sorting criterion, which sorts the elements by using operator <.

  如果你想要改变它的排序方法,需要传递额外的参数,例如:

 typedef set<int,greater<int> > IntSet;

  Note that you have to put a space between the two ">" characters. ">>" would be parsed as shift operator, which would result in a syntax error.

二、multiset

If you want to use a multiset rather than a set, you need only change the type of the container (the header file remains the same):

   typedef multiset<int> IntSet;

A multiset allows duplicates, so it would contain two elements that have value 1. Thus, the output of the program would change to the following:

   1 1 2 3 4 5 6

例如:
// stl/mmap1.cpp

   #include <iostream>
#include <map>
#include <string>
using namespace std; int main()
{
//type of the collection
typedef multimap<int, string> IntStringMMap; IntStringMMap coll; //set container for int/string values //insert some elements in arbitrary order
//- a value with key 1 gets inserted twice
coll.insert(make_pair(,"tagged"));
coll.insert(make_pair(,"a"));
coll.insert(make_pair(,"this"));
coll.insert(make_pair(,"of"));
coll.insert(make_pair(,"strings"));
coll.insert(make_pair(,"is"));
coll.insert(make_pair(,"multimap")); /* print all element values
*- iterate over all elements
*- element member second is the value
*/
IntStringMMap::iterator pos;
for (pos = coll.begin(); pos != coll.end(); ++pos) {
cout << pos->second << ' ';
}
cout << endl;
}
												

最新文章

  1. 【Python千问 2】Python核心编程(第二版)-- 欢迎来到Python世界
  2. VHDL TestBench基础(转)
  3. Python之re模块
  4. TJOI2010中位数
  5. MyBatis mysal 日报表,月,年报表的统计
  6. Ubuntu下一个好用的终端
  7. Java7 新特性: try-with-resources
  8. idea 执行maven 命令
  9. Cloud Foundry 组件
  10. 023.Zabbix自定义(邮箱)脚本告警-02
  11. ftp上传下载工具类
  12. idea_debug
  13. ES6必知必会 (九)—— Module
  14. centos崩溃后如何修复
  15. In c++ access control works on per-class basis not on per-object basis.
  16. POJ_3414 Pots 【复杂BFS】
  17. NO.002-2018.02.07《越人歌》先秦:佚名
  18. linux系统基础文件属性
  19. 有向图强连通分量的Tarjan算法及模板
  20. C# 读取Ini配置文件类

热门文章

  1. MySQL DELETE
  2. 网络编程Socket之TCP
  3. 绘图时,根据size()和自定义rect编程的区别
  4. InstallShield Basic MSI工程常见问题解答[转]
  5. echarts的使用
  6. extjs之TypeError: d.read is not a function解决方案
  7. 《asp.net mvc3 高级编程》第四章 模型
  8. js与jquery获取父元素,删除子元素的不同方法
  9. PHP进度条
  10. 堆排序(Heap Sort)的C语言实现