Reputation: 8277
I have a piece of code manipulating a map<int,int>
object. Let's say that at some point I want to double all the entries, keys and values. Is a there a way to do it in place, without creating a new map, looping and entering updated entries?
My concern is saving memory space.
Upvotes: 2
Views: 211
Reputation: 20015
You can traverse the map in reverse order of key for positive keys, in order to circumvent side effects, and create the new key/value pairs. You can do the equivalent for negative keys.
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
int main() {
map<int, int> m = {
{10, 20},
{-5, 23},
{-10, 7},
{20, 30},
{15, 21},
{18, 2},
};
for (auto it = m.begin(); it != m.end() && it->first < 0; it = m.erase(it)) {
m[it->first * 2] = 2 * it->second;
}
for (auto it = m.rbegin(); it != m.rend() && it->first > 0; it++) {
m[it->first * 2] = 2 * it->second;
m.erase(----it.base());
}
for (auto &p: m) {
printf("%d, %d\n", p.first, p.second);
}
}
Output:
-20, 14
-10, 46
20, 40
30, 42
36, 4
40, 60
Upvotes: 1
Reputation: 20264
Doubling the values is possible like this:
std::map<int,int> my_map;
for(auto& item:my_map){
item.second*=2; // double all values
}
However, it is not possible to double the Key
since item
is from the type std::pair<const int,int>
. Notice the const
for the Key
.
Suggestion:
I think std::map
is not best container for this case. Try this way:
std::vector<std::pair<int,int>> my_simi_map;
for(auto& my_simi_map){
item.first*=2; // double all keys
item.second*=2; // double all values
}
Edit:
My concern is saving memory space.
If it is just memory problem then you can pick an item from the map and insert a doubled version of it in the new map and directly delete it from the old map. In this case you will loose the size of just one element of the map not a whole another map.
Upvotes: 2