lm******@gmail.com wrote:
Actually if I can ask another question.... i thought i had it working
but it turns out I only partially have it working.... for some reason
it's not figuring out which begin() method to use... I have the
following methods:
iterator begin();
const_iterator begin() const;
And if I rename the second one to something like cbegin() it works
exactly as the std::map::const_iterator begin(); does. But if I leave
it as defined above I get the following compile error:
StrIntMap.cpp: In function `static void StrIntMap::test()':
StrIntMap.cpp:57: no match for `StrIntMap::const_iterator & =
StrIntMap::iterator'
StrIntMap.hh:150: candidates are: class StrIntMap::const_iterator &
StrIntMap::const_iterator::operator =(const StrIntMap::const_iterator
&)
gmake: *** [StrIntMap.o] Error 1
Any thoughts??
The error says it can't convert an "iterator" to a "const_iterator &"
(note the reference .. &) !
This is a different problem.
In this case it looks like you have somthing like (speculating):
M::const_iterator & foo()
{
M::iterator x;
return x;
}
A reference is kind of a special thing in C++, it like a pointer but
looks like an object. The speculation code above tries to return a
reference (pointer) to an object that it needs to create (temporary) but
since it's returning from a function, there is no way to allocate one
without it being destroyed.
Try returning by value.
M::const_iterator foo()
{
M::iterator x;
return x;
}
Now, you can make a copy of the iterator.
You could also generate a cons_iterator (by calling begin() const) but
you still have a problem with returning temporaries. (look in the FAQ).
#include <iostream>
#include <ostream>
#include <map>
int main()
{
typedef std::map<int,int> T;
T l_map;
const T & l_const_map;
l_map[1] = 1;
l_map[2] = 2;
T::const_iterator l_iter3 = l_const_map.begin();
T::iterator l_iter3 = l_const_map.begin(); // illegal.
}