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:
- Insert new object Z into map A
- (“Child”-class) Change the stuff in the returned object Z
- In every update cycle, iterate through the objects in map A and use the actual data loaded into object “A-Z” when updating…
The particular overload of
insertthat you’re using returns anstd::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:Notice that I’m returning a reference where you were returning a pointer and that the key type is
const unsigned int, notunsigned int. You can usemap_type::value_type, too (wheremap_typeis 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.