search map avoids const methods
Apr 25, 2009 at 11:40am UTC
Hello folks,
I am trying to compile the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream>
#include <string>
#include <map>
using namespace std;
class cfos
{
private :
map<int , string> diccfo;
public :
void setcfo (int c, string d) const
{
diccfo[c] = d;
};
string& getcfo (int c)
{
return diccfo[c];
};
void print() const
{
map<int , string>::iterator pdiccfo;
for (pdiccfo = diccfo.begin();
pdiccfo != diccfo.end();
++pdiccfo)
cout << pdiccfo->first << '\t'
<< pdiccfo->second
<< '\n' ;
};
};
int main()
{
cfos cfocoll;
cfocoll.setcfo(1, "one" );
cfocoll.setcfo(2, "two" );
cfocoll.print();
cout << cfocoll.getcfo(1) << endl;
return 0;
}
however, this error occurs:
passing ‘const std::map<int, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<int>, std::allocator<std::pair<const int, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >]’ discards qualifiers
Changing the map to mutable, I get to compile it, but the methods print () and setcfo () will be able to modify the map, what conceptually would not be good.
Any suggestions?
Last edited on Apr 26, 2009 at 3:25pm UTC
Apr 25, 2009 at 12:20pm UTC
Replace
map<int , string>::iterator pdiccfo;
with
map<int , string>::const_iterator pdiccfo;
Apr 25, 2009 at 1:21pm UTC
Well, this solves my problem with the print() function.
To solve the get() function I did this:
1 2 3 4
const string& getcfo (int c) const
{
return (diccfo.find(c))->second;
};
Has anybody a more elegant solution?
Thanks a lot!!
Last edited on Apr 26, 2009 at 3:26pm UTC
Apr 25, 2009 at 3:00pm UTC
What if diccfo.find(c)
returns diccfo.end()
?
Topic archived. No new replies allowed.