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


    本文主要是使用了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;
    }
    


    一些细节的地方说明,请看源码中的注释,谢谢!



  • 相关阅读:
    JQuery:自动触发事件
    SQL Server 取日期时间部分
    使用IIS 7.0 / 7.5 时配置HttpModules需要注意
    Winform:中直接打开指定文件
    jQuery 时间获取扩展
    喵星史话(一)——猫的起源
    2013年的环法
    ie8下奇怪的问题:float:left之后,右侧的div会影响左侧
    虚假IP和DNS污染
    android中setBackgroundResource和setBackgroundDrawable和用法
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3220198.html
Copyright © 2020-2023  润新知