std::map 反向遍历
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;?
??? }??
總結
以上是生活随笔為你收集整理的std::map 反向遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 方程AX=b的解的讨论(特解、通解、零空
- 下一篇: c语言实现排列组合:实现matlab中的