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;
}
#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
- std::map 反向遍历
- map容器的反向遍历
- std::map遍历删除某些元素问题
- C++遍历中删除std::map元素
- Qt QMap与std map的遍历
- QMap和std::map的遍历
- C++遍历中删除std::map元素
- 突然发现std::map的迭代器是有序遍历的
- std::map&&std::set
- std::map & std::hash_map
- std::map
- std::map
- std::map
- std::map
- std::map
- std::map
- std::map
- std::map
- 读懂diff
- pwd VS dirname $0
- R语言实现聚类分析
- 【汇编语言/底层开发】2、CPU的寄存器
- display:block、inline和inline-block的区别(转载)
- std::map 反向遍历
- Caused by: java.lang.OutOfMemoryError: Java heap space错误原因及解决方法
- SQL语句的添加、删除、修改
- Vim命令合集
- performSelector,带多个参数,NSInvocation, NSMethodSignature
- Codeforces 451E Devu and Flowers(容斥原理)
- C++项目——实现Time类中的运算符重载
- 今年股市绝对有戏,要外快的来哦
- lucene 查询 (转载)