Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change map 's second component?

Tags:

c++

dictionary

#include <iostream>
#include <map> 
using namespace std;
 
int main() {
    map<int, int> ma;
 
    //   원소를 추가 하자!!
    ma.insert(make_pair(100, 2));  // key 값 : 1 , value : 3
    ma.insert(make_pair(101, 3)); // key 값 : 3,  value : 13
    ma.insert(make_pair(102, 2)); // key 값 : 3,  value : 13
    ma.insert(make_pair(103, 3)); // key 값 : 3,  value : 13
    ma.insert(make_pair(104, 1)); // key 값 : 3,  value : 13
 
    // make_pair 형식으로 저장 했으므로
    // key 값은 fisrt 로 접근 value 값은 second 로 접근한다.
    for (auto iter : ma) {
        cout << "key : " << iter.first << " value : " << iter.second << '\n';
    iter.second = iter.second + 1;
    }
    cout << "\n" << "\n";
 
    for (auto iter : ma) {
        cout << "key : " << iter.first << " value : " << iter.second << '\n';
    }

    cout << "\n" << "\n";
    return 0;
}

Actually , I want to change the value of second component of pair.

iter.second = iter.second + 1;

This code can't change the thing... How can I change ???

like image 875
차현대 Avatar asked Feb 12 '26 02:02

차현대


1 Answers

The auto keyword in C++ always tries to infer a non-reference type, so in your case it infers iter as being type std::pair<const int, int>. This is not a reference type, so the values from the map get copied into the iter variable, and so any changes made to iter are not reflected in the map itself.

You can write auto& instead to force an lvalue-reference type:

for (auto& iter : ma) { // <-- Notice ampersand here
  iter.second = iter.second + 1;
}
like image 136
Silvio Mayolo Avatar answered Feb 13 '26 15:02

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!