STL之set && multiset
2014-09-23 10:07
281 查看
一、set在了解关联容器set之前,让我们先来看看下面这个例子,并猜测该例子输出什么:
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:
// 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(3); coll.insert(1); coll.insert(5); coll.insert(4); coll.insert(1); coll.insert(6); coll.insert(2); /* 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.二、multisetIf 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(5,"tagged")); coll.insert(make_pair(2,"a")); coll.insert(make_pair(1,"this")); coll.insert(make_pair(4,"of")); coll.insert(make_pair(6,"strings")); coll.insert(make_pair(1,"is")); coll.insert(make_pair(3,"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; }
相关文章推荐
- STL - 常用关联容器代码 - set & multiset
- STL之set&multiset容器(笔记)
- C++/STL关联容器-集合-multiset&set的用法
- STL之set&multiset使用简介
- 转自http://blog.sina.com.cn/daylive——C++ STL set&multiset
- STL_set&multiset
- STL中的set/multiset小结
- STL中set与multiset的区别
- STL概览-关联容器set,multiset,map,multimap(四)
- STL之关联容器(set /map /multiset /multimap)
- stl的set,multiset, map, multimap, deque, list, stack, queue, priority_queue
- STL set multiset map multimap unordered_set unordered_map example
- 关联容器:set multiset map multi…
- STL学习笔记----5.容器 set 和 multiset
- STL概览-关联容器set,multiset,map,multimap
- Set & MultiSet
- STL学习笔记4--set and multiset
- STL学习笔记----5.容器 set 和 multiset
- STL源码解析-05关联容器-01map&set
- STL:set(multiset)