本文介绍了当我在地图(C ++)中使用const_iterator时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我在使用map的const_iterator时遇到错误,下面是我的代码,请帮帮我,非常感谢!
Employ.cc
Hello,everyone,I have encountered an error when I use map''s const_iterator,following are my codes,please help me,thank you very much!
Employ.cc
<br />
<pre lang="cs">#include <string><br />
#include <iostream><br />
using namespace std;<br />
class Employ{<br />
friend class EmployCompare;<br />
public:<br />
Employ(const string& firstname,const string& lastname):firstname_(firstname),lastname_(lastname){}<br />
string getFirstName(){return firstname_;}<br />
string getLastName(){return lastname_;}<br />
private:<br />
string lastname_;<br />
string firstname_;<br />
};<br />
class EmployCompare{<br />
public:<br />
bool operator()(const Employ& e1,const Employ e2) const{<br />
if(e1.lastname_ < e2.lastname_){<br />
return true;<br />
}<br />
else if(e1.lastname_ == e2.lastname_){<br />
return (e1.firstname_ < e2.firstname_);<br />
}<br />
else{<br />
return false;<br />
}<br />
}<br />
};</pre><br />
main.cc
main.cc
<br />
<pre lang="xml">#include <algorithm><br />
#include <iostream><br />
#include <iterator><br />
#include <map><br />
#include "Employ.cc"<br />
using namespace std;<br />
int main( )<br />
{<br />
map<Employ,string,EmployCompare> employMap;<br />
Employ em1("lily","beautiful"),em2("boge","hardwork"),em3("relation","love"),em4("result","nice");<br />
employMap[em1] = "tester";<br />
employMap[em2] = "programmer";<br />
employMap[em3] = "coder";<br />
employMap[em4] = "student";<br />
map<Employ,string,EmployCompare>::const_iterator it = employMap.begin();<br />
while(it != employMap.end()){<br />
cout << it->first.getFirstName() << "--" << it->first.getLastName() << " is " << it->second << endl;<br />
}<br />
return 0;<br />
}</pre><br />
错误:
And the error:
<br />
<pre lang="vb">../src/main.cc:21: error: passing ‘const Employ’ as ‘this’ argument of ‘std::string Employ::getFirstName()’ discards qualifiers<br />
../src/main.cc:21: error: passing ‘const Employ’ as ‘this’ argument of ‘std::string Employ::getLastName()’ discards qualifiers</pre><br />
非常感谢!
Thank you very much!
推荐答案
#include <iostream>
#include <vector>
#include "Employ.h"
using namespace std;
int main( )
{
Employ em1("lily","beautiful"),em2("boge","hardwork"),em3("relation","love"),em4("result","nice");
vector<Employ> vec;
vec.push_back(em1);
vec.push_back(em2);
vec.push_back(em3);
vec.push_back(em4);
for(vector<Employ>::iterator it = vec.begin();it!=vec.end();it++)
{
cout << it->getFirstName() << "--" << it->getLastName() << endl;
}
return 0;
}
这篇关于当我在地图(C ++)中使用const_iterator时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!