STL - Map #2

이승덱·2021년 7월 21일

CPP

목록 보기
56/70
#include <iostream>

#include <vector>

#include <list>

#include <deque>

#include <map>

using namespace std;

// Map

class Player {

public:

 Player():_playerId(0) {

 }

 Player(int playerId):_playerId(playerId) {

 }

public:

 int _playerId; //플레이어를 구분

};

// pair의 대략적 형태

template<typename T1, typename T2>

class Pair {

public:

 T1 t1;

 T2 t2;

};

int main()

{

 // 연관 컨테이너(시퀀스 컨테이너와는 다르다)

 

 // map : 균형 이진 트리 (AVL)

 // -> 자신보다 낮은 값 : 왼쪽, 높은 값 : 오른쪽 에 저장

 // -> 그와 동시에 BF를 계산하여 균형을 맞춘다.

 // - 노드 기반

 

 class Node {

 public:

 Node* Left;

 Node* Right;

 //DATA

 pair<int, Player*> _data;

 //int _key;

 //Player* value;

 };

 srand(static_cast<unsigned int>(time(nullptr)));

 // (key, value)

 map<int, int> m;

 pair<map<int, int>::iterator, bool> ok;

 ok=m.insert(make_pair(1, 100)); // 해당 iterator와 true 반환

 ok=m.insert(make_pair(1, 100)); // insert는 중복삽입이 안됨, bool이 false로 반환

 // -> 즉 덮어씌우는 개념이 아니라 무시함

 // 10만명 입장

 for (int i = 0;i < 100000;i++) {

  // 데이터 두개를 멤버변수로 들고있음

 m.insert(pair<int, int>(i,i*100));

 }

 // 5만명 퇴장

 for (int i = 0;i < 50000;i++) {

 int randomValue = rand() % 50000;

 // Erase By Key

 //m.erase(randomValue);

 }

 // Q) 특정 Id의 유저를 찾고 싶다!

 // A) 매우 빠르게 찾을 수 있음!

 unsigned int count = 0;

 count=m.erase(10000);

 count = m.erase(10000); // 삭제가 되지 않았다면 0을 반환

 map<int, int>::iterator findIt = m.find(10000); // map의 iterator를 반환

 if (findIt != m.end()) { // 데이터를 못찾을 경우 m.end() 값을 가리킴

 cout << "찾음" << endl;

 findIt->second = 200;

 }

 else {

 cout << "못찾음" << endl;

 m.insert(make_pair(10000, 10000));

 }

 // map 순회 

 for (map<int, int>::iterator it = m.begin();it != m.end();++it) {

 pair<const int, int>& p = (*it);

 int key = (*it).first;

 int value = it->second;

 }

 // 없으면 추가, 있으면 수정 version 2

 m[5] = 500; // 5라는 키 값이 없으면 추가하고 value를 500으로 저장

 // 5라는 키 값이 있다면 value를 500으로 변경

 // [] 연산자 주의점: 대입을 하지 않더라도

 // (Key/Value) 형태의 데이터가 추가된다.

 m.clear();

 for (int i = 0;i < 10;i++) {

 cout << m[i] << endl; //없으면 추가한다는 기능이 있기 때문에 노드가 추가됨

 //따라서 있는지 없는지 확인하고자 할 때는 이 문법을 사용하면 안됨

 }

 // 넣고 insert,[]

 // 빼고 erase

 // 찾고 find, [](추가되는걸 고려)

 // 반복자 map::iterator (*it) -> pair<key,value>&

 // 결론 : 특정 id를 찾는 경우 vector보다 빠르게 처리가 가능하다

 return 0;

}
profile
공부 기록용 블로그입니다

0개의 댓글