使用map迭代器中遇到的问题——非const转成const类型造成的编译错误
来源:互联网 发布:网络传销诈骗防范措施 编辑:程序博客网 时间:2024/06/05 07:30
在使用迭代器的时候,遇到下面这个问题,值得注意:
非const转成const类型造成的编译错误;
这种类型的错误,在每本书上都会被提及,但是真正在使用的的时候还是会出错,所以要好好对待这些不起眼的错误。
错误代码示例:
#include <iostream>#include<set>#include<string>#include<map>using namespace std;int main(){ map<string,int> m; string str; int n; cin>>str; cin>>n; m.insert(pair<string,int>(str,n)); for( map< string,int >::iterator it=m.cbegin(); it != m.cend(); ++it)//错误发生在这一行 { cout<<it->first<<" "<<it->second<<endl; } return 0;}
在for循环条件的地方,在编写程序的时候,考虑到map的操作都是进行读操作,不涉及写操作,打算使用cbegin()和cend();
但是我给迭代器的类型是 map< string,int >::iterator,是一个非const类型;
此时是将一个const类型的迭代器转换成一个非const类型,必然会发生错误。
正确代码:
#include <iostream>#include<set>#include<string>#include<map>using namespace std;int main(){ map<string,int> m; string str; int n; cin>>str; cin>>n; m.insert(pair<string,int>(str,n)); for( map< string,int >::const_iterator it=m.cbegin(); it != m.cend(); ++it)//使用const_iterator { cout<<it->first<<" "<<it->second<<endl; } return 0;}
或者:
#include <iostream>#include<set>#include<string>#include<map>using namespace std;int main(){ map<string,int> m; string str; int n; cin>>str; cin>>n; m.insert(pair<string,int>(str,n)); for( auto it=m.cbegin(); it != m.cend(); ++it)//直接使用auto类型更方便;但在平时不建议使用auto,这样可能会忘记迭代器的真正类型是什么,得不偿失! { cout<<it->first<<" "<<it->second<<endl; } return 0;}
阅读全文
0 0
- 使用map迭代器中遇到的问题——非const转成const类型造成的编译错误
- 遇到的const问题
- const造成的一些错误记录
- 编译DirectX Tutorials时遇到的错误:"const wchar_t *" 类型的实参与 "LPCSTR" 类型的形参不兼容
- const与非const类型赋值问题
- c++类型-const的使用
- 两则const的使用引发的编译错误
- c语言const 转为非const的问题
- 使用非const指针修改const int的值
- map作为const引用的问题
- 一个和const有关的编译错误
- 模板中const导致的编译错误
- const map的初始化及使用
- C++ 使用 extern const 编译失败的问题
- 临时变量作为非const的引用进行参数传递引发的编译错误
- const 类型的函数不能返回非const类型的引用
- const 类型的函数不能返回非const类型的引用
- const类型的指针是否可变问题
- 2.陶陶摘苹果
- 自定义ViewPager,可垂直、水平滑动,支持循环展示
- zookeeper 永久监听节点 来保证集群间一致性
- hihocoder1634-Puzzle Game
- SSH项目访问action报错
- 使用map迭代器中遇到的问题——非const转成const类型造成的编译错误
- EMI
- CAB6伺服穿气袋位置更改问题
- DSS 代码分析【Reliable UDP之数据重传】
- leetcode 242. Valid Anagram
- 如何处理前任留下的代码
- 接口调试插件RESTED使用post的方法
- 数据结构与算法分析(Java语言描述)(32)—— 使用 Kruskal 算法求有权图的最小生成树
- 混合游戏环境:让人类一直身处在物联网中(作业 全靠google)