Reputation: 145
How do I correctly and efficiently return a pair from a newly inserted pair to a map?
inline pair<unsigned int, T> *createObj(unsigned int UID){
static pair<unsigned int, T> ret;
objList.insert(pair<unsigned int, T>(UID, T()));
if (UID_Counter <= UID)
UID_Counter = UID+1;
ret = make_pair(UID, objList.find(UID)->second);
return &ret;
}
The above returns a object to use, but whatever I change in ret does not change in the "real pair" in the map...
Basically what i want to achieve is:
Upvotes: 2
Views: 1312
Reputation: 35449
The particular overload of insert
that you're using returns an std::pair<iterator, bool>
. In particular the first member of that pair is an iterator to either the element that was newly inserted or the element that was already present. Thus:
pair<const unsigned int, T>&
createObj(unsigned int UID)
{
auto inserted = objList.insert(pair<unsigned int, T>(UID, T()));
if (UID_Counter <= UID)
UID_Counter = UID+1;
return *inserted.first;
}
Notice that I'm returning a reference where you were returning a pointer and that the key type is const unsigned int
, not unsigned int
. You can use map_type::value_type
, too (where map_type
is the type of your container).
If you're wondering why your code wasn't working, it's because you were storing a copy of the mapped object inside ret
, so any modification through the pointer you returned would only affect that copy.
Upvotes: 4