reassign keys in a map

S

Shailesh Humbad

I have a class and map like this:

class MyObject {
...
};

map<int, MyObject> Box;

Now, I want to reassign the keys of one or more of the pairs in Box
based on another map<int, int> that stores the key assignment like
(old, new). Since MyObject may be big, this should be done without
invoking the MyObject copy constructor. For example, if the map was
like (1 => a, 2 => b, 3 => c), then it might change to (3 => a, 1 =>
b, 2 => c). I know the algorithm, but I'm not very good with STL. If
someone has already worked this out, some sample code would be helpful.

// Create temporary map<int, MyOBject> tempBox

// For each pair in map<Old, New>
// Add <New, Box[Old].MyObject> into tempBox

// Swap the maps
Box.swap(tempBox);
 
S

Shailesh Humbad

Okay, I figured out the algorithm, just need a suggestion on how to
avoid copying of the MyObject class.


map<int, MyObject> Box;

void
ReassignKeys(std::map<int, int>& ReassignmentMap)
{
map<int, MyObject> tempBox;
map<int, int>::iterator ReassignmentIterator;
map<int, MyObject>::iterator ObjectsIterator;

// Do nothing if nothing to reassign.
if(ReassignmentMap.size() == 0)
{
return;
}

// Loop through each reassignment and add the object to the new
for(ReassignmentIterator = ReassignmentMap.begin();
ReassignmentIterator != ReassignmentMap.end();
ReassignmentIterator++)
{
// First make sure the old key exists
assert(Box.end() !=
Box.find(ReassignmentIterator->first));

// Now get the object based on the old key, and add it to the
// temporary container with the new key
tempBox.insert(map<int, MyObject>::value_type(
ReassignmentIterator->second, // new key
Box[ReassignmentIterator->first]) ); // object, use old key

// Remove the object from the original container
Box.erase(ReassignmentIterator->first);
}

// Add any objects that weren't reassigned to the new container
for(ObjectsIterator = Box.begin();
ObjectsIterator != Box.end(); ObjectsIterator++)
{
// Make sure the key doesn't already exist in the new map
assert(tempBox.end() == tempBox.find(ObjectsIterator->first));

// Insert the pair into the new map
tempBox.insert(map<int, MyObject>::value_type(
ObjectsIterator->first, ObjectsIterator->second));
}

// Erase the old map
Box.clear();

// Now swap the old with the new
Box.swap(tempBox);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top