重新排列 std::map 中的键

Rearrange keys in std::map

我有一张看起来像这样的地图:

0, 1234

1, 5678

2, 9012

现在,例如,我删除了键为 1 的条目,因此映射如下所示:

0, 1234

2, 9012

现在我想重新排列键,使地图看起来像这样:

0, 1234

1, 9012

知道怎么做吗?

你想要的听起来很不合逻辑。键是唯一的,用于查找值(非常快)。现在您想更改密钥,这很奇怪。您可能需要平面类型的列表类型。

您应该查看 std::liststd::vector。当您删除项目时,索引会自动 'updated'。

您只能通过擦除之前的元素并使用新密钥重新插入来实现

使用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;
        });
}

输出

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