使用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
原创粉丝点击