Having probs updating the key of a multimap record. I've tried various examples from here and there but no luck using mingw 3.4.2 Everything apart from update of key works (insert, erase, find ...) So below a simplified example, with between commented asterisks just one of my attempts of where the problem is.
You can't modify the key in a map. If you look closely at the value_type of a std::map<T1, T2>, you'll see that it is std::pair<const T1, T2>. What you should do instead is remove the element and insert an element with the new key.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
But if you think this is a dangerous practise please get back.
The map is stored in sorted order. That's how it gets fast lookups. Even unordered_maps still rely on the key not changing, because then its hash value would change.
Can you change the key? Yeah, const_cast lets you do all sorts of bad things. Odds are the map's find() method won't be able to find the key you changed anymore though. In fact it may not be able to find a *lot* of the things in there, because you corrupted its data structure. Don't do it.
I'm guessing that 'first' and 'second' are pointers.
first and second are whatever you specify them to be. Their types correspond to the key and value type of the map.
So why no dummy for the key as in:
perhaps I'm asking too much
You can safely change any part of the key object except for whatever field(s) it's ordering predicate (usually operator<) relies on for comparison (or the hash function in the case of an unordered_map).
However, if you've got extra data tagging along, one wonders why that data is in the key object rather than the value object. The very fact that you're asking this question points to a problem with your design.
Many tx Lindley and indeed D_Drmmr - I would have happily driven into the black hole and soon been lost without your prompt replies.
I had read among others an article suggesting this was a bad thing but when the examples within it failed I rather lost faith in its content. I also found other examples of how it might be done lying around the web (dangerous place you know the web!!).
So I guess I must insert a new record and delete the old one. Seems a little tedious after finding so many slick bits of C++ but c'est la vie.
There may be implementations out there that allow key modification. Doing so would only require moving the node into its new position after the change. However, it wasn't included in the STL because that's a fairly rare operation, and the remove/insert combo isn't significantly less efficient.