Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning iterator from STL map when using object as a key

Tags:

c++

iterator

stl

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;
}
like image 524
ManNamedJed Avatar asked May 12 '26 06:05

ManNamedJed


2 Answers

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.

like image 133
Alok Save Avatar answered May 13 '26 19:05

Alok Save


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) );
like image 33
Sergey Avatar answered May 13 '26 20:05

Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!