Consider following snippet:
MapT map;
map["A"] = 1;
map["B"] = 2;
map["C"] = 3;
map["D"] = 4;
map["E"] = 5;
MapT mapSecond;
mapSecond["A"] = 10;
mapSecond["B"] = 20;
mapSecond["C"] = 30;
mapSecond["X"] = 4;
mapSecond["Y"] = 5;
MapT::const_iterator itSecond = mapSecond.begin();
MapT::iterator it = map.begin();
for (; itSecond != mapSecond.end(); ++itSecond)
{
std::pair<MapT::iterator, bool> pair = map.insert(std::make_pair(itSecond->first, itSecond->second));
if (!pair.second)
{
pair.first->second = itSecond->second;
}
}
for (; it != map.end(); ++it)
{
std::cout << it->first << " " << it->second << std::endl;
}
I assume using the returned iterator from insert is the most efficient version.
However at first, I did just thought assigning the iterators only works fine (note I am not dereferencing the iterator anymore here).
1.)
// assigning the dereferenced iterator (i.e.: the underlying std::pair)
// resulting in no match for binary '=' operator for const std::string
*pair->first = *itsecond;
I know its obsolete as I already matched the key and only care about the value. This error occurs only because of the key being a const std::string If I am not completely out of my mind :D
2.)
// assigning the iterator itself
// does not compile as long as itSecond is of type const_iterator ?
// does nothing in case itSecond is of type iterator
pair.first = itSecond;
This is the thing I actually don't understand. How is the assignment of an iterator in a std::map supposed to behave? Although I do program C++ for a few years already, I never encountered a scenario where I did so for any container. I have not found a lot of information about assigning iterators in general during a bit of research.
And finally would there be an even more elegant way of doing what I want to achieve (using C++11 features, maybe C++14)?