집합과 포함 여부
Coddy의 GDScript 개발자를 위한 C++ 코스 레슨. 48개 중 15번째.
GDScript에는 집합 자료형이 없습니다. 일반적인 관용구는 구성원을 키로 사용하고 값은 무시하는 Dictionary이며, in 또는 has로 테스트합니다. 기존 키를 다시 할당하면 값만 덮어쓰며, keys()는 삽입 순서대로 반환됩니다. C++의 std::set은 실제 집합입니다. 고유한 키를 비교자 순서대로 저장하며, 기본값은 오름차순이므로 삽입 순서와 순회 순서는 다릅니다. insert는 second 멤버가 키가 새로 추가된 경우에만 true인 쌍을 반환하고, contains 또는 count로 구성원인지 테스트합니다.
GDScript
extends Node
func _ready():
var seen := {8: true, 3: true}
print(8 in seen, " ", 5 in seen)
seen[8] = true
seen[5] = true
print(seen.keys())
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
std::set<int> s{8,3};
std::cout<<std::boolalpha<<s.insert(8).second<<" "<<s.insert(5).second<<"\n";
for(int x:s)std::cout<<x<<"\n";
}
각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 출력과 대상 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 정수. 서로 다른 값의 개수를 반환하세요.
exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 수정할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 명시된 경우 공개 API 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 signed int 범위에 들어갑니다. 별도 언급이 없으면 텍스트는 ASCII입니다.
직접 해보기
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<int> v;int n;while(in>>n)v.push_back(n);std::cout<<unique_count(v)<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
GDScript 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러