[TIL] c++ map

map에서 find


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
#include <iostream>
#include <map>

using std::cout; using std::cin;
using std::endl; using std::map;
using std::string;

int main(){
    std::map<string, string> m1 = { {"h", "htop"},
                                   {"k", "ktop"},
                                   {"t", "ttop"},
                                   {"r", "rtop"},
                                   {"w", "wtop"},
                                   {"p", "ptop"} };

    string key = "h";

    auto item = m1.find(key); //item은 주소값이 담긴다, item->first: 첫번째값(key 값) , item->second: 두번째값(value 값)
    if (item != m1.end()) { //m1.end()는
        cout << "Key exists!  -  {" <<
            item->first << ";" << item->second << "}\n";
    } else {
        cout << "Key does not exist!" << endl;
    }

    return EXIT_SUCCESS;
}

map 순회


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
/* map example */
#include <map>
#include <string>
#include <iostream>

using std::map;
using std::string;
using std::cout;
using std::endl;

int main(void){
	// <int, string> fair map test
	map<int, string> m;
	map<int, string>::iterator i;

	m.insert( map<int, string>::value_type(1, "Hello") );
	m.insert( map<int, string>::value_type(2, "World") );

	// map 순회
	for(i = m.begin(); i != m.end(); i++){
		cout << "[" << i->first << "] " << i->second << endl;
	}

	// direct select
	cout << m[1] << endl;

	// <string, string> fair map test
	map<string, string> m2;
	map<string, string>::iterator j;

	m2.insert( map<string, string>::value_type("a", "Hello") );
	m2.insert( map<string, string>::value_type("123", "World") );

	// map 순회
	for(j = m2.begin(); j != m2.end(); j++){
		cout << "[" << j->first << "] " << j->second << endl;
	}

	// direct select
	cout << m2["123"] << endl;
}
0%