프로그래밍/C++

STL set, multi(map, set)

우대비 2022. 11. 7. 19:27
반응형

<keyType, valueType> 형식으로 만들었던 map
그렇다면 "key가 곧 value"인 상황에서는 어떻게 해야할까!?

바로 set을 사용하면 됨

 

- SET

 // 생성
 t<int> s;
// 넣기
s.insert(10);
s.insert(20);
s.insert(50);
s.insert(40);
s.insert(80);
s.insert(60);
s.insert(30);
s.insert(70);
s.insert(90);

//빼고
s.erase(40);

//찾고
set<int>::iterator findit = s.find(50);
if (findit == s.end())
{
    cout << "못찾음" << endl;
}
else
{
    cout << "찾음" << endl;
}

// 순회
for (set<int>::iterator it = s.begin(); it != s.end(); ++it)
{
    cout << *it << endl;
}

 

 

map을 사용하는데 "같은 key에 여러 값"을 넣을 수는 없을까????

- MULTIMAP

// 생성
multimap<int, int> mm;

// 넣기
mm.insert(make_pair(1, 100));
mm.insert(make_pair(1, 200));
mm.insert(make_pair(1, 300)); // key : 1, value : 100, 200, 300
mm.insert(make_pair(4, 400));
mm.insert(make_pair(5, 500));

// 빼고
unsigned int count = mm.erase(1);

// 찾고
multimap<int,int>::iterator mulIt = mm.find(1);
if (mulIt != mm.end())
    mm.erase(mulIt); // value : 100, 200, 300 전부 삭제됨

// 순회

// 두개의 multimap iterator를 담고 있는 Stuct(pair)에 key값이 1인 iterator를 넣음
pair < multimap<int, int>::iterator, multimap<int, int>::iterator> itPair;
itPair = mm.equal_range(1);

// lower_bound는 가장 밑에 있는거
multimap<int, int>::iterator itBegin = mm.lower_bound(1);

// upper_bound는 가장 위에 있는거라고 생각하면 됨
multimap<int, int>::iterator itEnd = mm.upper_bound(1);


// 아래의 두 for문은 완전히 같은 기능을 함
for (multimap<int, int>::iterator it = itPair.first; it != itPair.second; ++it)
{
	cout << it->first << " " << it->second << endl;
}

for (multimap<int, int>::iterator it = itBegin; it != itEnd; ++it)
{
    cout << it->first << " " << it->second << endl;
}

 

 

그렇다면 set도 같은 key를 여러번 넣을 수 있지않을까!?

- MULTISET

// 생성
multiset<int> ms;

// 넣기
ms.insert(100);
ms.insert(100);
ms.insert(100);
ms.insert(200);
ms.insert(200);

// 찾기
multiset<int>::iterator findIt = ms.find(100); // 하나만 찾음

// 두개의 multiset::iterator를 담고있는 struct에 키 값이 100인 애들을 전부 넣음
pair < multiset<int, int>::iterator, multiset<int, int>::iterator> itPair2;
itPair2 = ms.equal_range(100);

// multimap과 동일함
multiset<int>::iterator itBegin2 = ms.lower_bound(100);
multiset<int>::iterator itEnd2 = ms.upper_bound(100);

// multimap과 동일
for (multiset<int>::iterator it = itBegin2; it != itEnd2; ++it)
{
    cout << *it<< endl;
}

for (multiset<int>::iterator it = itPair2.first; it != itPair2.second; ++it)
{
    cout << *it << endl;
}

 

반응형
LIST

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

중괄호 초기화와 initializer_list  (0) 2022.11.08
STL algorithm  (0) 2022.11.08
STL map  (0) 2022.11.06
STL deque 정리  (1) 2022.11.04
STL list 정리  (0) 2022.11.03