공대생의 비망록

[C++] map 컨테이너에 데이터 추가하기 insert()? [] 연산자? 본문

Programming Language/C, C++

[C++] map 컨테이너에 데이터 추가하기 insert()? [] 연산자?

myungsup1250 2022. 5. 3. 18:45

[] 연산자를 이용한 방법 ( map[key] = value; ) 으로는 key에 값이 새로 생성된 것인지, 기존 값을 update한 것인지 알 수가 없다.

그러나 map 컨테이너의 insert() 메소드를 사용하면 이를 구분할 수 있다!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <map>
 
using namespace std;
 
int main () {
    map<stringint> map;
 
    pair<map<char,int>::iterator,bool> ret;
    ret = map.insert(make_pair("test"500));
    if (ret.second == false) {
        cout << "element \"test\" already exists";
        cout << " prev value: " << ret.first->second << endl;
    } else {
        cout << "element \"test\" newly inserted";
        cout << " inserted value: " << ret.first->second << endl;
    }
 
    return 0;
}
 
cs
Comments