박하의 나날

[24]템플릿과 자주 사용되는 컨테이너들_2

프로그래밍/Unreal

1. C++ STL버전 Set

C++ set은 하나로 정렬된 아이템들의 모음이다. 장점은 set의 요소들을 정렬된 상태로 유지한다는 점이다.

가장 쉽고 빠르게 값들의 모음을 정렬하는 방법은 같은 값을 set으로 넣어버리는 것.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<set> 
using namespace std;
int main(){
    set<int> intSet;
    intSet.insert(7);
    intSet.insert(7);
    intSet.insert(8);
    intSet.insert(1);
    for(set<int>::iterator it = intSet.begin(); it != intSet.end(); ++it){
        cout << *it << endl;
    }
}
//결과 : 1 7 8
cs

inSet.begin() intSet의 맨 처음요소 중 포인터를 가진 반복자를 변환한다.

intSet.end() 실제 셋의 마지막 요소 이전의 위치.

요소를 검색하려면 find() 멤버 함수를 사용한다. set에서 찾고 싶은 요소를 발견하면 그 위치의 포인터를 가진 반복자를

얻게 된다. 없으면 set.end()를 얻게 된다.

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
set<int>::iterator it = intSet.find(7);
if( it != intSet.end() ){
    //intSet안에 7이 있고 *it은 그 값을 가지고 있다.
    cout << "Found" << *it << endl;
}
 
EX)
#include<iostream>
#include<string>
#include<set>
using namespace std;
int main(){
    set<string> names;
    while(names.size() < 3){
        cout << names.size() << "개의 이름이 있습니다. 이름을 입력하세요." << endl;
        stirng name;
        cin >> name;
        names.insert(name); // 이미 있다면 입력되지 않는다.
    }
    //이름 출력
    for( set<string>::iterator it = names.begin(); it != names.end(); ++it){
        cout << *it <<endl;
    }
}
    
cs

 

2.C++ STL map

Tmap은 내부를 정렬하지 않고 map은 정렬한다.

it->first 로 키에 접근하고 it->second 로 값에 접근한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
    map<stringint> items;
    items.insert(make_pair("apple"12));
    itmes.insert(make_pair("orange"1));
    items.insert(make_pair("banana"3));
    items["kiwis"= 44//대괄호를 이용한 입력
    //이름 출력
    for( map<stringint>::iterator it = items.begin(); it != items.end(); ++it){
    cout<< "items [ " << it->first << " ] = " << it->second << endl;
    }
}
//결과 : items [ apple ] = 12 ...
cs

 

STL map의 <키, 값> 을 검색하려면 find 멤버 함수를 사용하면 된다.

EX) 유저에게 다섯개의 아이템과 각 아이템의 수량을 받아 빈 map에 넣기. 정렬된 순서대로 결과 출력.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
    map<stringint> items;
    cout << "아이템을 5개와 개수를 입력해주세요 : " <<endl;
    while(items.size() < 5){
        cout<< "아이템을 입력해주세요" <<endl;
        string itemName;
        cin >> itemName;
        count<< "개수를 입력해주세요" << endl;
        int itemNum;
        cin>>itemNum;
        items[ item ] = itemNum;
    }
    for(map<stringint>::iterator it = items.begin(); it!= items.end(); ++it){
    cout<<"items["<<it->first<<"] = "<<it->second << endl;
    }
}
cs

 

 

 

 

'프로그래밍 > Unreal' 카테고리의 다른 글

[25] 백팩(인벤토리), 아이템줍기  (0) 2017.06.10
0607/그냥정리  (0) 2017.06.07
[23] 템플릿과 자주 사용되는 컨테이너들  (0) 2017.06.04
[22]npc 대화상자  (0) 2017.06.01
[21]언리얼 오브젝트 처리  (0) 2017.05.22