영넌 개발로그

[C++ STL] container set 집합 본문

코딩/C++

[C++ STL] container set 집합

영넌 2020. 12. 7. 20:38

container 중 set 이라는 것은 집합을 의미합니다. 값을 중복없이 저장하는 데에 자주 사용하고 집합 내에 유무를 체크하는데에 사용된다. 따라서 중복성 검사를할 때에 사용되는 자료구조 이기도하다. (check if element already exists) 예를 들어 문장 단위로 잘라서 set으로 만든 후, 그 문장이 다른 set에 나타나는지 안나타나는지에 사용하여 표절 검사를 할 수 있다. 

 

집합 내에 유무를 체크하기 위해서는 method find를 사용한다. <returns iterator for target element>

set은 증가하는 형태로 저장하는 특징이 있기 때문에 정렬된 형태로 뽑아낼 수 있다.  

삽입할 때는 method insert를 사용한다. 반환할 때는 쌍으로 <iterator, bool>을 반환한다. bool 값은 중복성에 따라 true와 flase를 반환하고,  iterator는 어렵게 생각하지 않고 그냥 pointer라고 생각하면 된다. 예를 들어 set 에 1,2,3,4가 있는데 3을 insert하려 하면 iterator에는 3의 위치와 bool 에는 false를 반환하여 <2,false> 값이 반환된다.

 

 

set for int>

#include <iostream>
#include <set>

using namespace std;

int main() {
	
	set<int> myset;

	myset.insert(5);
	myset.insert(3);
	myset.insert(1);
	myset.insert(2);
	myset.insert(4);

	//1이 있으면 그 위치에 대한 iterator
	//    없으면, myset.end()를 넘겨줌
	auto pos = myset.find(1);

	if (pos == myset.end()) {
		cout << "Not found" << endl;
	}
	else {
		cout << "Found" << endl;
	}
    
    
    
	//첫번째값은 res.first / 두번째 값은 res.second 로 볼 수 있다.
	pair<set<int>::iterator, bool> res = myset.insert(30);

	if (res.second == false) {
		cout << "Alread exist" << endl;
	}
	else
	{
		cout << "Insertion success" << endl;
	}
    
    
    	//지우기
   	myset.erase(30);
    
    
    	//출력
   	 //iterator
    	for (auto e = myset.begin(); e != myset.end(); e++) {
		cout << *e << " ";
	}
    
   	 //reference
   	for(auto& e: myset){
    		cout << e << " ";
    	}

	return 0;
}

 

 

 

set for object>

#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;

}

Comments