Search

[STL] set, container set 집합

생성일
2023/01/20 13:49
태그
C++

<set> container set 집합

Set (집합)
값을 중복없이 저장하는 데에 자주 사용하고 집합 내에 유무를 체크하는데 사용
중복성 검사할 때 사용되는 자료구조
set은 증가하는 형태로 저장하는 특징이 있기 때문에 정렬된 형태로 뽑아낼 수 있다
#include <set> set<int> s;
C++
복사

삽입

s.insert(5); s.insert(10);
C++
복사

제거

s.erase(10);
C++
복사

예시(1) - int

#include <iostream> #include <set> using namespace std; int main() { set<int> s; s.insert(5); s.insert(3); s.insert(1); s.insert(2); s.insert(4); // 1이 있으면, 그 위치에 대한 iterator // 1이 없으면, s.end()를 넘겨준다 auto pos = s.find(1); if (pos == s.end()) { cout << "Not found" << '\n'; } else { cout << "Found" << '\n'; } // 첫번째 값은 res.first, 두번째 값은 res.second로 볼 수 있다. pair<set<int>::iterator, bool> res = s.insert(30); if (res.second == false) { cout << "Already exist" << '\n'; } else { cout << "Insertion success" << '\n'; } s.erase(30); // 출력, iterator for (auto e = s.begin(); e != s.end(); e++) { cout << *e << " "; } cout << "\n"; // reference for (auto& e : s) { cout << e << " "; } return 0; }
C++
복사

예시(2) - word

#include <iostream> #include <set> #include <string> using namespace std; class Person { public: string name; int age; Person(string _name, int _age) : name(_name), age(_age) {}; bool operator< (const Person& p) const { if (name < p.name) { return true; } else if (name == p.name) { if (age < p.age) { return true; } } return false; } }; int main() { set<Person> myset; myset.insert(Person("John1", 30)); myset.insert(Person("John2", 21)); myset.insert(Person("John3", 31)); myset.insert(Person("John4", 19)); myset.insert(Person("John5", 25)); auto pos = myset.find(Person("John5", 25)); if (pos == myset.end()) { cout << "Not found" << endl; } else { cout << "Found" << endl; } pair <set<Person>::iterator, bool> res = myset.insert(Person("John6", 19)); res = myset.insert(Person("John6", 99)); if (res.second == false) { cout << "Already exist" << endl; } else { cout << "Insertion success" << endl; } for (auto& e : myset) { cout << e.name << " is " << e.age << "years old." << endl; } cout << endl; myset.erase(Person("John3", 31)); for (auto& e : myset) { cout << e.name << " is " << e.age << "years old." << endl; } return 0; }
C++
복사