How to implement different `std::map insert()` behaviour depending on the existence of the pair being inserted?

StackOverflow https://stackoverflow.com/questions/17292798

  •  01-06-2022
  •  | 
  •  

Question

I'd like the std::map insert() function to behave differently depending on whether the pair to insert is already in the map or not - if it is not, insert it as usual, if it is already there, increment the counter stored inside a second of the pair. How can I do that without additional querying the existence (since the insertion queries it anyway)?

I'm tracking a lot of event records, each of them containing the source and receiver ID's. Events are stored as std::vector. I'm also trying to maintain the dictionary of sources and receivers records as std::map where the first of the pair (key) contains the ID, while the second contains some source info plus std::vector that tracks all the events that refer to that source.

So, when the event refers to currently absent source, the insertion should proceed as normal, but if the referred source is already in the dictionary, the insertion should add the referring event number to std::vector of the existing dictionary element.

Était-ce utile?

La solution

Looks like one have to keep the result of the insert function, analyse it and behave accordingly:

typedef std::map<int, T> itmap;
typedef std::pair<itmap::iterator, bool> itinsresult;
//...
itmap m;
int i;
T t;
//...
itinsresult result = m.insert(std::make_pair(i, t));
if (result.second) // new element inserted
{
   //...
}
else // element already exists
{
   (*result.first).do_something();
   // ...
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top