기술 블로그

#include <map> 본문

C++ STL

#include <map>

parkit 2019. 3. 22. 15:45
728x90
반응형

#include <map>


자동 정렬 및 중복 제거 그리고 이진트리 구조를 가진다.



http://www.cplusplus.com/reference/stl/



위의 링크에서 각종 STL을 볼 수 있으며, map도 있다.


<Key, Value> 구조를 가진다.



find, erase 등등 많이 있으며,


위의 홈페이지에서 코드도 볼 수 있다.



나는 간단하게만 올리겠다.



map은 Key가 중복되면 안 된다.


중복되면, 런타임 에러가 발생하므로,


중복을 허용하려면 multimap을 이용한다.



마지막으로



map.count(key)랑 map[key]를 구분하자.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <math.h>
#include <algorithm>
#include <map>
#include <set>
#include <tuple>
 
#pragma warning(disable:4996)  
#pragma comment(linker, "/STACK:336777216")
 
using namespace std;
 
map<intstring> m;
 
// map<Key, Value>
 
int main(void)
{
    string s;
 
    for (int i = 0; i < 5; i++)
    {
        cin >> s;
 
        m.insert({ 0, s }); // pair 형태로 Key와 Value 둘 다 저장
    }
    
    auto itr = m.begin();
 
    printf("\n\n<map 출력>\n");
 
    while (itr != m.end())
    {
        cout << itr->first << " = " << itr->second << '\n';
        // itr->first = Key
        // itr->second = Value
 
        ++itr; // ++itr;을 꼭 써줘야 한다.(정렬, 탐색, 조회 등등 할 때에 필요하다. 아니면 for문을 써도 됨.)
    }
 
    printf("\n\n");
 
    printf("<map count>\n");
 
    for (int i = 0; i < 5; i++)
    {
        cout << m.count(i) << '\n';
    }
    
    return 0;
}
cs





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <math.h>
#include <algorithm>
#include <map>
#include <set>
#include <functional>
#include <unordered_map>  
#include <unordered_set>  
#include <tuple>
#include <sstream>
 
#pragma warning(disable:4996)  
#pragma comment(linker, "/STACK:336777216")
 
using namespace std;
 
int main(void)
{
    map<intint> m;
    m[1= 1;
    m[1= 2;
    m[1= 3;
 
    cout << m.count(1<< '\n'
    // 키 값인 1을 가진 value의 개수는 당연히 키 값의 개수이다. 
    // map은 중복 X
    
    cout << m[1<< '\n'// 키 값이 1인 value의 값 자체
 
    multimap<intint> mm;
    mm.insert(pair<intint>(11));
    mm.insert(pair<intint>(12));
 
    cout << mm.count(1<< '\n';
    // 키 값인 1을 가진 value의 개수는 당연히 키 값의 개수이다. 
    // multimap은 중복을 허용하기 때문에 키 값의 개수는 여러 개가 가능하다.
 
    return 0;
}
cs












728x90
반응형

'C++ STL' 카테고리의 다른 글

vector<vector<int> > v; 정렬 전, 정렬 후  (0) 2019.05.04
string to int(문자열을 int로 변환)  (0) 2019.04.16
#include <tuple>  (0) 2019.03.18
2차원 배열 fill로 초기화.(feat memset)  (2) 2019.01.10
next_permutation  (0) 2019.01.09