I have an issue with returning an iterator from an STL map using an object as a key.
The code compiles when only performing a map.insert(), but will not compile the line attempting to use the iterator returned from a map.insert().
The compiler error is "error: no match for 'operator='"
Please see the offending line immediately preceding the return statement in the code snippet below.
Thanks for any assistance!
#include <map>
using namespace std;
class Keys {
public:
Keys(int k1, int k2) :
key1(k1), key2(k2) {
}
bool operator<(const Keys &right) const {
return (key1 < right.key1 && key2 < right.key2);
}
int key1;
int key2;
};
int main() {
std::map<Keys, int> mymap;
map<Keys,int>::iterator myitr;
mymap.insert(std::pair<Keys, int>(Keys(3, 8), 5));
myitr = mymap.insert(std::pair<Keys, int>(Keys(1, 2), 3));
return 0;
}
You need to use:
pair<map<Keys,int>::iterator,bool> ret;
ret = mymap.insert(std::pair<Keys, int>(Keys(1, 2), 3));
Note the return values in the std::map::insert() documentation.
You need to use an appropriate overloaded function of std::map, that returns an iterator. For now, you are using std::map::insert with one parameter and it returns std::pair but not an iterator. You should use this:
std::map<>::iterator std::map::insert( iterator _where, value_type val );
So, your code should looks like this:
myitr = mymap.insert( std::begin( mymap ), std::make_pair( Keys(1, 2), 3) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With