I need to add, store and delete some pairs of objects, e.g. Person–Hobby. Any person can have several hobbies and several persons can have the same hobby. So, multimap is a good container, right?
Before adding a pair I need to know, if it’s not added yet. As I can see here there is no standard class-method to know, if the concrete pair e.g. Peter-Football exists in the MM. Thus, I’ve written a method which returns a positive integer (equal to the distance between mm.begin() and pair iterator) if the pair exists and -1 otherwise.
Then I need to delete some pair. I call my find method, which returns, some positive integer. I call myMultiMap.erase(pairIndex); but the pair is not being deleted for some reason. That is my problem. Obviously the erase method needs an iterator, not the int. The question is: how do I convert an integer to an iterator?
Thanks!
UPDATE:
I’ve tried this c.begin() + int_value but got an error error: no match for ‘operator+’ on this line….
Not that I favour your approach, but if the
intis distance betweenbegin()and the iterator in question, you can just useor
to get the iterator. The second version is needed for iterators which are not random-access-iterators.
In the interest of your personal sanity (and the program’s speed), I’d suggest you return the iterator directly in some form.
There are many possible interfaces that solve this one way or the other. What I would call the “old C way” would be returning by an out parameter:
use it:
or
This is not idiomatic C++, but Linus would be pleased with it.
The second possible and theoretically sound version is using something like
boost::optionalto return the value. This way, you return either some value or none.Use:
or
Third possible solution would be going the
std::set::insertway, ie. returning a pair consisting of a flag and a value:Use: