Skip to content

Instantly share code, notes, and snippets.

@flomnes
Last active February 21, 2023 08:59
Show Gist options
  • Save flomnes/008920c58ba607c91d201b42a543507c to your computer and use it in GitHub Desktop.
Save flomnes/008920c58ba607c91d201b42a543507c to your computer and use it in GitHub Desktop.
Change a map by reference, not by value
#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