std::map 反向遍历

来源:互联网 发布:淘宝耐克阿迪正品店 编辑:程序博客网 时间:2024/05/22 06:09
1、反向遍历:可以使用反向迭代器reverse_iterator反向遍历map映照容器中的数据,它需要rbegin()和rend()方法指出反向遍历的起始位置和终止位置。
#pragma warning(disable:4786)
#include<iostream> 
#include<map>
#include<string> 
using namespace std; 
 
int main() 

    map<int,char> m; 
    //插入元素,按照键值大小插入黑白树
    m[25]='m'; 
    m[28]='k'; 
    m[10]='x'; 
    m[30]='a'; 
    m.erase(28); 
         
    for(map<int,char>::reverse_iterator rit=m.rbegin();rit!=m.rend();rit++) 
    cout<<(*rit).first<<","<<(*rit).second<<endl;    
    return 0; 
    } 
2、元素搜索:使用find()方法搜索某个键值,如果搜索到了,则返回该键值所在的迭代起位置否则,返回end()迭代器位置,由于map采用黑白树搜索,所以搜索速度极快。当然也可以用count()方法,但是需要如果想直接使用的话再使用键值搜索,需要两次查找,这时候就不如find功能好。

程序代码:
#pragma warning(disable:4786)
#include<iostream> 
#include<map>
#include<string> 
using namespace std; 
 
int main() 

    map<int,char> m; 
    //插入元素,按照键值大小插入黑白树 
    m[25]='m'; 
    m[28]='k'; 
    m[10]='x'; 
    m[30]='a'; 

    map<int,char>::iterator it;
    it=m.find(28);
    if(it!=m.end())
          {
           cout<<(*it).first<<":"<<(*it).second<<endl;            
            }
    else cout<<"not find it"<<endl;  
    return 0; 
    }  
0 0
原创粉丝点击