您的位置:首页 > 其它

STL中map,set的基本用法示例

2013-07-27 20:56 513 查看
本文主要是使用了STL中德map和set两个容器,使用了它们本身的一些功能函数(包括迭代器),介绍了它们的基本使用方式,是一个使用熟悉的过程。

map的基本使用:

#include "stdafx.h"
#include<iostream>
#include<set>
#include<string>
#include<vector>
#include<map>

using namespace std;

int main()
{
//定义map对象
map<string,float> myMap;
myMap["jack"]=98.5;
myMap["bomi"]=98.0;
myMap["Kate"]=97.6;

map<string,float>::iterator itm;
for(itm=myMap.begin();itm!=myMap.end();itm++)
{
//按照键值与映照的数据输出
cout<<(*itm).first<<" : "<<(*itm).second<<endl;
}

int k=0;
cin>>k;
return 0;
}

set的基本使用示例:

#include "stdafx.h"
#include<iostream>
#include<set>
#include<string>
#include<vector>

using namespace std;

int main()
{
set<int> mySet;
mySet.insert(8);
mySet.insert(1);
mySet.insert(12);
mySet.insert(6);
mySet.insert(8);            //这里因为前面已经插入了8,重复元素,不会插入。

set<int>::iterator its;  //set容器的迭代器

cout<<"正向遍历:"<<" ";
for(its=mySet.begin();its!=mySet.end();its++)   //正向遍历
{
cout<<*its<<" ";
}
cout<<endl<<"反向遍历:"<<" ";

set<int>::reverse_iterator rit;            //set的逆向迭代器
for(rit=mySet.rbegin();rit!=mySet.rend();rit++)
{
cout<<*rit<<" ";
}

//删除键值为6的元素
mySet.erase(6);
cout<<endl<<"删除之后的反向遍历:"<<" ";
for(rit=mySet.rbegin();rit!=mySet.rend();rit++)
{
cout<<*rit<<" ";
}

//set中元素的检索
mySet.insert(17);
mySet.insert(10);

cout<<endl;
its=mySet.find(10);            //使用迭代器来查找,没找到就返回end().
if(its!=mySet.end()) cout<<"找到了"<<*its<<endl;
else cout<<"没有找到查询的元素"<<endl;

its=mySet.find(100);
if(its!=mySet.end()) cout<<"找到了"<<*its<<endl;
else cout<<"没有找到查询的元素"<<endl;

int k=0;
cin>>k;
return 0;
}


一些细节的地方说明,请看源码中的注释,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: