gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:28:19 25 4
gpt4 key购买 nike

美好的一天,

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

例子:

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
}

key其实就是它在table上显示的objectID

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

我不能使用行 ID 作为键,因为我经常使用 objectID 引用表

如果 map 元素在插入时保持它们的顺序,我将更容易重新分配映射到键的值,即使 Unordered Map 也不是这样

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


目前我想到了这个。欢迎任何有效的解决方案

//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

最佳答案

您的问题的可能解决方案可能是简单地使用 std::vector包含对象标识符。按照您希望它们显示的顺序将对象 ID 插入 vector 中,然后从头到尾遍历 vector 以显示项目。如果您随后从 vector 中删除一个对象 ID,您会自动将其下方的对象 ID 向上移动一级。

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


另一种可能的解决方案是使用您现在拥有的方案,但不要将 std::map 中的值视为行,而只是将其视为排序顺序。但是你可能会更好地使用 Boost bimap相反,这样你就可以双管齐下。

关于c++ - std::map - 在项目删除后重新排序映射值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25804502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com