Menu
CoddyTech

동등성과 해싱

Coddy의 C++ 개발자를 위한 Dart 코스 레슨. 48개 중 40번째.

C++의 std::unordered_set은 해시 함수 객체인 std::hash<T> 또는 TagHash처럼 전달한 함수를 사용해 키를 찾고, operator==로 키를 비교합니다. 반면 std::set은 operator<로 키의 순서를 정합니다. Dart의 해시 컬렉션은 키 자체의 ==와 hashCode를 호출합니다. 두 경우 모두 같은 객체는 일관된 해시 값과 안정적인 동등성 관련 필드를 가져야 합니다.

같은 객체는 같은 hashCode 값을 가져야 하지만, 해시 충돌이 동등성을 증명하는 것은 아닙니다. 객체를 해시 컬렉션에 저장하는 동안 동등성에 영향을 주는 상태를 안정적으로 유지하세요. Dart에서 hashCode를 재정의하지 않고 ==만 재정의하면 집합과 맵이 제대로 작동하지 않습니다.

완전한 C++ 프로그램:

#include <cstddef>
#include <functional>
#include <iostream>
#include <string>
#include <unordered_set>
struct Tag{std::string text;bool operator==(const Tag&other)const{return text==other.text;}};
struct TagHash{std::size_t operator()(const Tag&t)const{return std::hash<std::string>{}(t.text);}};
int main(){std::unordered_set<Tag,TagHash> tags{Tag{"a"},Tag{"a"}};std::cout<<tags.size()<<"\n";}

완전한 Dart 프로그램:

class Tag{final String text;const Tag(this.text);@override bool operator ==(Object other)=>other is Tag&&text==other.text;@override int get hashCode=>text.hashCode;}
void main(){print({Tag('a'),Tag('a')}.length);}
challenge icon

챌린지

쉬움

final 공개 필드가 있는 불변 Key(int row,int column)을 구현하세요. 두 Key는 두 좌표가 모두 일치할 때만 서로 같습니다. operator ==와 hashCode를 일관되게 재정의하세요. 입력은 완전한 정수 좌표 쌍으로 구성됩니다. Set을 사용해 서로 다른 키의 개수를 세고 그 개수를 반환하세요. 좌표 범위는 -100부터 100까지입니다.

편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart는 입력을 파싱하고 출력을 반환하며, 잠긴 드라이버는 공개 API를 별도로 테스트하고 결과를 줄바꿈 문자 하나와 함께 출력합니다.

코드는 Key.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.

직접 해보기

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Key.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final a=Key(2,3),b=Key(2,3);check(a==b && a.hashCode==b.hashCode && a!=Key(3,2));check({a,b}.length==1);
stdout.writeln(solve(input));
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 Dart의 모든 레슨

직접 연습해 보세요: 온라인 Dart 컴파일러