Reputation: 11
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?
Upvotes: 0
Views: 116
Reputation: 14863
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
Upvotes: 2
Reputation: 326
You can do it only by erasing the previous element and re-insert it with a new key
Upvotes: 0
Reputation: 19800
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.
Upvotes: 0