您的位置:首页 > 编程语言 > C语言/C++

[c++ primer] 关联容器_set,multimap

2016-10-09 11:26 281 查看
set类型

set类型与map类型操作相似,其只有键值,按顺序排列,且为const类型,不能进行修改

例示代码:

#include <iostream>
#include <string>
#include <map>
#include <set>
using namespace std;

set<int> iset;
set<int>::iterator it;

int main()
{
int n;
scanf("%d",&n);
//插入
for(int i=1;i<=n;i++)
iset.insert(i);

//count函数返回set中元素的个数,在set中要么为0,要么为1
cout <<"the number of 1:"<< iset.count(1)<<endl;

//find返回所指向元素的迭代器
it = iset.find(1);

cout << *it << endl;

//其值不能修改,为const类型
//*it =2;

cout << *it << endl;

return 0;
}



multi
map类型

multimap类型和map类型相似,其一个键值可以对应多个值

代码例示:

#include <iostream>
#include <string>
#include <map>
#include <set>
#include <utility>
using namespace std;

typedef multimap<int,string>::iterator map_it;
multimap<int,string> imap;
map_it it;

int main()
{
int n,num;
scanf("%d",&n);
//插入 multimap 可以重复插入键值一样的pair
for(int i=1;i<=n;i++)
{
imap.insert(make_pair(i,"kaixin "));
imap.insert(make_pair(i,"is very "));
imap.insert(make_pair(i,"happy!"));
}

//count函数返回set中元素的个数
num = imap.count(1);
cout <<"the number of 1:" << num << endl;

//第一种遍历方法

//find返回所指向键值第一个的 迭代器
it = imap.find(1);
cout << it->second << endl;

//根据个数,遍历输出
for(int i=1;i<=num;i++,it++)
cout<< it->second ;
cout << endl;

//第二种遍历方法

// lower_bound 返回元素的首个迭代器
// upper_bound返回元素末尾迭代器的下一个
map_it beg,end;

beg = imap.lower_bound(1);
end = imap.upper_bound(1);
while(beg!=end)
{
cout << beg->second;
beg++;
}
cout << endl;

//第三种遍历方法

//equal_range 返回pair 类型,相当于 lower_bound和upper_bound的组合
pair<map_it,map_it> pos = imap.equal_range(1);
while(pos.first!=pos.second)
{
cout<<pos.first->second;
pos.first++;
}
cout << endl;
//输出 pos.second
cout << pos.second->first<<pos.second->second<<endl;

return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: