简体   繁体   中英

Rearrange keys in std::map

I have a map looking like this:

0, 1234

1, 5678

2, 9012

Now, for example I remove the entry with key 1, so the map looks like this:

0, 1234

2, 9012

Now I want to rearrange the keys, so that the map looks like this:

0, 1234

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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