알고리즘 코드카타
Set
#include <iostream>
#include <set>
using namespace std;
int main() {
/* 생성자 */
set<int> set; // 오름차순, 기본 값 : less<int>
//set<int, greater<int>> set; //내림차순
/* 삽입, 삭제 */
set.insert(30);
set.insert(40);
set.insert(10);
set.insert(20);
set.insert(50);
set.insert(50); // 중복 저장 x
set.erase(20);
for (int i : set) {
cout << i << " ";
}
cout << "\n";
for (auto it = set.begin(); it != set.end(); it++) {
cout << *it << " ";
}
cout << "\n";
/* 값 탐색 */
// 1. 삽입 성공여부 확인
auto it = set.insert(50); // pair< set<int>::iterator, bool >
if (it.second) {
cout << *it.first << "삽입 성공\n";
}
else {
cout << *it.first << "삽입 실패\n";
}
// 2. 개수 탐색. set은 중복이 불가하므로 0 또는 1의 값
cout << "원소 60 개수 : " << set.count(60) << "\n";
// 3. find 함수로 탐색
if (set.find(50) == set.end()) { // find는 존재하지 않으면 set.end()를 리턴
cout << "원소 50은 현재 없다.\n";
}
else {
cout << "원소 50은 현재 존재한다.\n";
}
return 0;
}
프로그래머스 - 두 개 뽑아서 더하기
정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요.
#include <string>
#include <vector>
#include <set>
using namespace std;
vector<int> solution(vector<int> numbers) {
vector<int> answer;
set<int> temp;
for(int i=0;i<numbers.size()-1;i++){
for(int j=i+1;j<numbers.size();j++){
temp.insert(numbers[i]+numbers[j]);
}
}
for(int i:temp)
answer.push_back(i);
return answer;
}
중복 X, 오름차순일 때는 Set을 사용해서 간단하게 구현할 수 있다.
참고
https://notepad96.tistory.com/25
[STL] Set 생성, 삽입, 삭제 등 사용법
1. set set은 특정 기준에 의하여 원소들이 자동 정렬되는 노드 기반 컨테이너이다. set은 기본적으로 오름차순(less) 정렬이고 greater 조건자를 줌으로써 내림차순으로 정렬할 수도 있다. set은 유일
notepad96.tistory.com
'내배캠Unreal_TIL > C++' 카테고리의 다른 글
| [TIL] 2026-01-23 | <string> find, <algorithm> find (0) | 2026.01.23 |
|---|---|
| [TIL] 2026-01-20 | C++ int to char / char to int / int to string / string to int (0) | 2026.01.20 |
| [TIL] 2026-01-15 | C++ 캐스트(cast) 연산자 (0) | 2026.01.15 |
| [TIL] 2026-01-12 | C++ 프로그래머스 행렬의 덧셈, 직사각형 별찍기, 최대공약수와 최소공배수 (0) | 2026.01.12 |
| [TIL] 2025-12-29 | C++에서 중요한 건 메모리, 수명, 비용 (0) | 2025.12.29 |