Server/C++

STL) Map과 Set

Juzdalua 2024. 7. 28. 00:43

Map

Key:Value 클래스

Key를 기준으로 정렬되어 검색에 용이한 트리.

#include <stdio.h>
#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<int, char> aMap;
    aMap.insert({1, 'A'});
    aMap.insert(make_pair(2, 'B'));
    aMap[1] = 'a'; // 배열에서 index가 들어갈 위치에 키값이 들어간다.

    map<int, char>::iterator aMapIter;
    for (aMapIter = aMap.begin(); aMapIter != aMap.end(); aMapIter++)
    {
        cout << aMapIter->first << ", " << aMapIter->second << endl;
    }

    if (aMap.find(1) != aMap.end())
    {
        cout << "1 Value: " << aMap.find(1)->second << '\n';
    }
    
    if (aMap.find(3) != aMap.end())
    {
        cout << "empty Value: " << aMap.find(3)->second << '\n';
    }

    return 0;
}

https://learn.microsoft.com/ko-kr/cpp/standard-library/map-class?view=msvc-170

 

map 클래스

C++ STL(표준 템플릿 라이브러리) 'map' 클래스에 대한 API 참조로, 각 요소가 데이터 값과 정렬 키를 모두 포함하는 쌍인 컬렉션에서 데이터를 저장하고 검색하는 데 사용됩니다.

learn.microsoft.com


Set

Key만 존재하는 Map 클래스.

중복이 불가능하고 정렬되어 존재함.

#include <stdio.h>
#include <iostream>
#include <set>

using namespace std;

int main()
{
    set<int> intSet;
    intSet.insert(10);
    intSet.insert(99);
    intSet.insert(4);
    intSet.insert(1);

    set<int>::iterator intSetIter;
    for(intSetIter = intSet.begin(); intSetIter != intSet.end(); intSetIter++){
        cout << *intSetIter << endl;
    }
    
    set<char> charSet;
    charSet.insert('A');
    charSet.insert('a');
    charSet.insert('C');
    charSet.insert('f');

    set<char>::iterator charSetIter;
    for(charSetIter = charSet.begin(); charSetIter != charSet.end(); charSetIter++){
        cout << *charSetIter << endl;
    }

    if(charSet.find('A') != charSet.end()){
        charSet.erase('A');
    }

    return 0;
}

https://learn.microsoft.com/ko-kr/cpp/standard-library/set-class?view=msvc-170

 

set 클래스

컬렉션에서 데이터를 저장하고 검색하는 데 사용되는 C++ 표준 라이브러리 컨테이너 클래스 'set'에 대한 API 참조입니다.

learn.microsoft.com

 


<set>
<map>
Key만 가지고 있는 구조
Key-Value 쌍의 구조
set
map
Tree 구조, O log(N)
중복 불가능
정렬됨
multiset
multimap
Tree 구조, O log(N)
중복 가능
정렬됨
unordered_set
unordered_map
Hash 구조, O(1)
중복 불가능
정렬안됨
unordered_multiset
unordered_multimap
Hash 구조, O(1)
중복 가능
정렬안됨

 

'Server > C++' 카테고리의 다른 글

Lock  (0) 2024.07.29
쓰레드 (Thread)와 Atomic  (0) 2024.07.29
STL) Vector와 List - iterator  (0) 2024.07.27
STL) Vector와 List  (0) 2024.07.27
템플릿 (template)  (0) 2024.07.26