简体   繁体   English

重新排列 std::map 中的键

[英]Rearrange keys in std::map

I have a map looking like this:我有一个看起来像这样的 map:

0, 1234 0, 1234

1, 5678 1, 5678

2, 9012 2、9012

Now, for example I remove the entry with key 1, so the map looks like this:现在,例如我删除键 1 的条目,所以 map 看起来像这样:

0, 1234 0, 1234

2, 9012 2、9012

Now I want to rearrange the keys, so that the map looks like this:现在我想重新排列键,使 map 看起来像这样:

0, 1234 0, 1234

1, 9012 1、9012

Any idea how to do this?知道怎么做吗?

Use vector使用矢量

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    int j = 0;
    std::vector<int> v = {100, 200, 300};
    std::for_each(v.begin(), v.end(), [&j](auto const& p) {
        std::cout << "index = " << j++ << " value = " << p << std::endl;
        });

    /* Delete item at index = 1 */

    v.erase(v.begin() + 1);
    j = 0;
    std::for_each(v.begin(), v.end(), [&j](auto const& p) {
        std::cout << "index = " << j++ << " value = " << p << std::endl;
        });
}

Output Output

index = 0 value = 100
index = 1 value = 200
index = 2 value = 300
index = 0 value = 100
index = 1 value = 300

What you want sound very unlogical.你想要的听起来很不合逻辑。 The key is unique and is used to lookup values (very fast).键是唯一的,用于查找值(非常快)。 Now you want to change the key, this is weird.现在你想改变密钥,这很奇怪。 You likely need a flat type of list type.您可能需要一个扁平类型的列表类型。

You should look into std::list or std::vector .您应该查看std::liststd::vector The index is automatically 'updated' when you remove items.当您删除项目时,索引会自动“更新”。

You can do it only by erasing the previous element and re-insert it with a new key您只能通过擦除前一个元素并使用新密钥重新插入它来做到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM