Last active
February 21, 2023 08:59
-
-
Save flomnes/008920c58ba607c91d201b42a543507c to your computer and use it in GitHub Desktop.
Change a map by reference, not by value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
int main() { | |
std::map<int, int> m; | |
auto display_m = [&m](const char *msg) { | |
std::cout << msg << " "; | |
for (auto [k, v] : m) { | |
std::cout << "m[" << k << "] = " << v << std::endl; | |
} | |
}; | |
{ | |
m[4] = 2; | |
display_m("After init"); | |
} | |
{ | |
for (auto [k, v] : m) { | |
v = 4; | |
} | |
display_m("key-value, by value"); | |
} | |
{ | |
for (auto p : m) { | |
p.second = 5; | |
} | |
display_m("pair, by value"); | |
} | |
{ | |
for (auto &p : m) { | |
p.second = 5; | |
} | |
display_m("pair, by reference"); | |
} | |
} | |
// After init m[4] = 2 | |
// key-value, by value m[4] = 2 | |
// pair, by value m[4] = 2 | |
// pair, by reference m[4] = 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment