std :: map - 在项目擦除后重新排序映射值

时间:2014-09-12 09:01:53

标签: c++ stl stdmap

美好的一天,

我正在使用std :: map将表的行条目绑定到键项

示例:

std::map<int,int> myMap;

myMap[13]=0;
myMap[15]=1;
myMap[1]=2;
myMap[5]=3;
...
...

添加/更新项目操作

std::map<int,int>::iterator it;
it=result_RecordList.find(methodID);
if(it==result_RecordList.end())
{
    //new item , new row record
}
else
{
    //get record row id and update that item    
}

键实际上是表格上显示的objectID

删除第2行后;我希望myMap [5]现在映射到第2行。

我不能使用行id作为密钥,因为我经常使用objectID

引用该表

如果地图元素在插入时保持其顺序,我将更容易重新分配映射到键的值,即使无序地图不是这样

欢迎任何解决方案, 谢谢......


目前我已经想到了这一点。欢迎任何有效的解决方案

//after myMap erase item
std::map<int,int>::iterator itReassign;

for(itReassign=myMap.begin();itReassign!=myMap.end();itReassign++)
{//for loop
    if(itReassign->second>rowID)//all value above the rowID will be downshifted
    itReassign->second=itReassign->second-1;
}//for loop

2 个答案:

答案 0 :(得分:1)

问题的可能解决方案可能是简单地使用包含对象标识符的std::vector。按照您希望它们显示的顺序在向量中插入对象ID,然后在向量上从头到尾循环以显示项目。然后,如果您从向量中删除对象ID,则会自动&#34; shift&#34;它下方的物体ID向上迈出了一步。

但是,此解决方案将更改std::map的O(1)访问权限,以查找特定对象ID的行为O(n)。


另一种可能的解决方案是使用您现在拥有的方案,但不要将std::map中的值视为行,而只是作为排序顺序。但是你可能会更好地使用Boost bimap,所以你可以双向进行。

答案 1 :(得分:0)

使用您的新解决方案,您可以尝试使用upper_bound方法 http://www.cplusplus.com/reference/map/map/upper_bound/ 然后迭代直到结束

myMap.std::map<char,int>::iterator itup = = myMap.upper_bound (rowId);
while(itup!=myMap.end();++itup)
{
    (*itup)--;
}