[C++] C++ STL, 맵 (CMap) 예제
본문 바로가기

응용 프로그램 개발/C++, MFC, Windows

[C++] C++ STL, 맵 (CMap) 예제

728x90
반응형

STL 이란,

C++에서 제공하는 표준 템플릿 라이브러리(Standard Template Library)로

자료구조, 알고리즘 등을 편하게 사용할 수 있도록 해주는 라이브러리이다.

 

STL 은 크게 container, iterator, algorithm 으로 구성되는데

Container는 순차 컨테이너(sequence container), 연관 컨테이너(associative container)가 있다.

 

Associative Container 중 대표적인 CMap은 다음과 같이 사용한다.

 

CMap<CString, LPCTSTR, INT, INT> m_map;
int nVal = 0;
CString strKey = L"";

// 1. Add key and value
m_map.SetAt(L"AAA", 10);
m_map.SetAt(L"BBB", 20);
m_map.SetAt(L"CCC", 30);

// 2. LookUp key 'AAA'
if(m_map.Lookup(L"AAA", nVal))
{
    AfxMessageBox(_T("%d"), nVal);
}

// 3. Replace key and value
m.SetAt(L"AAA", 11);

// 4. Iterate Map
POSITION pos = m_map.GetStartPosition();
while( pos != NULL )
{
    m_map.GetNextAssoc(pos, strKey, nVal);
    AfxMessageBox(_T("%s = %d"), strKey, nVal);
}

// 5. Remove 'AAA'
m_map.RemoveKey(L"AAA");

// 6. Size of Map
AfxMessageBox(_T("size of Map = %d"), m_map.GetCount());

// . Remove all existing key pair
m_map.RemoveAll();

 

728x90
반응형