STL card does not add a pair after removing the first pairs
In this code snippet, I add a pair to the map and everything is fine, but when I remove a pair that is not the last, no more pairs are added in the map. What am I doing wrong?
SomeClass::add(Object object)
if (!object.empty())
{
ObjectList::iterator result = find(object.name());
if (result == ObjectList.end())
{
object.order(size() + 1);
ObjectList.insert(orderedObject(object.order(), object));
}
else
{
ObjectList[result->first] = object;
}
}
ObjectList and orderedObject are declared like this:
typedef std::pair<int, Object> orderedObject;
typedef std::map<int, Object> ObjectList;
This is the removal code:
SomeClass::eraseNamed(std::string aName)
{
if (!isEmpty())
{
ObjectList::iterator result;
result = find(aName);
if (result != ObjectList.end())
{
ObjectList.erase(result);
reorgObjectList();
return true;
}
}
return false;
}
For the search method:
ObjectList::iterator SomeClass::find(std::string aName)
{
ObjectList::iterator result = ObjectList.begin();
while (result != ObjectList.end())
{
if (aName == result->second.name())
return result;
result++;
}
return result;
}
and for reorgObjectList:
bool SomeClass::reorgObjectList()
{
ObjectList::iterator i=ObjectList.begin();
int j=1;
for (i = ObjectList.begin(); i != ObjectList.end(); ++i)
{
if(j!=i->second.order())
i->second.order(j);
j++;
}
return true;
}
Any suggestions???
Well you are setting the size of the map, it looks like it might cause problems.
So, if you have 3 things on the map, you will have
1 => Obj1
2 => Obj2
3 => Obj3
if you remove one of these elements, say in 1, you have
2 => Obj2
3 => Obj3
and then go to insert and set the key to "size () + 1" the size will return 2 and you will try to insert the key 2 + 1 == 3. 3 is already done. So it will either exceed or fail (not sure how your find works above).
Instead of inserting size + 1, I would check the last key and increment by 1 if that's how you want to manage the key.
a source to share