std :: map 키 클래스가 유효한 키가 되려면 어떤 요구 사항을 충족해야합니까?
주어진 클래스의 객체를 다른 객체에 매핑하고 싶습니다. 그러나 내가 키로 사용하려는 클래스는 내가 작성한 것이 아니고 struct
몇 가지 값 이있는 단순 합니다. std :: map은 그 내용을 순서대로 지정하고, 어떻게 수행하는지, 임의의 클래스를 키로 사용할 수 있는지 또는 정의해야하는 일련의 요구 사항 (연산자 및 그렇지 않은 것)이 있는지 궁금합니다.
그렇다면 연산자 맵 사용을 구현하는 클래스에 대한 래퍼를 만들 수 있습니다. 먼저 구현해야 할 것이 무엇인지 알아야하며 온라인에서 찾은 클래스에 대한 참조는이를 지정하지 않습니다.
키에 필요한 것은 복사 및 할당이 가능하기 만하면됩니다. 맵 내의 순서는 템플릿에 대한 세 번째 인수 (사용되는 경우 생성자에 대한 인수)에 의해 정의됩니다. 이 디폴트 로 std::less<KeyType>
는 기본값 <
운영자하지만, 기본값을 사용 할 필요가 없습니다. 비교 연산자를 작성하면됩니다 (가급적이면 함수 객체로).
struct CmpMyType
{
bool operator()( MyType const& lhs, MyType const& rhs ) const
{
// ...
}
};
엄격한 순서를 정의해야합니다. 즉, CmpMyType()( a, b )
true CmpMyType()( b, a )
를 반환하면 false를 반환해야하며, 둘 다 false를 반환하면 요소가 동일한 것으로 간주됩니다 (동등한 클래스의 구성원).
operator <를 정의해야합니다. 예를 들면 다음과 같습니다.
struct A
{
int a;
std::string b;
};
// Simple but wrong as it does not provide the strict weak ordering.
// As A(5,"a") and A(5,"b") would be considered equal using this function.
bool operator<(const A& l, const A& r )
{
return ( l.a < r.a ) && ( l.b < r.b );
}
// Better brute force.
bool operator<(const A& l, const A& r )
{
if ( l.a < r.a ) return true;
if ( l.a > r.a ) return false;
// Otherwise a are equal
if ( l.b < r.b ) return true;
if ( l.b > r.b ) return false;
// Otherwise both are equal
return false;
}
// This can often be seen written as
bool operator<(const A& l, const A& r )
{
// This is fine for a small number of members.
// But I prefer the brute force approach when you start to get lots of members.
return ( l.a < r.a ) ||
(( l.a == r.a) && ( l.b < r.b ));
}
대답은 실제로 "비교"템플릿 인수의 설명 아래에 링크 된 참조에 있습니다.
The only requirement is that Compare
(which defaults to less<Key>
, which defaults to using operator<
to compare keys) must be a "strict weak ordering".
Same as for set
: The class must have a strict ordering in the spirit of "less than". Either overload an appropriate operator<
, or provide a custom predicate. Any two objects a
and b
for which !(a<b) && !(b>a)
will be considered equal.
The map container will actually keep all the elements in the order provided by that ordering, which is how you can achieve O(log n) lookup and insertion time by key value.
'Development Tip' 카테고리의 다른 글
Java 클래스 이름의 유효한 문자 (0) | 2020.11.08 |
---|---|
토렌트에서 DHT는 어떻게 작동합니까? (0) | 2020.11.08 |
내가 하위 디렉토리에있을 때 로컬 git 저장소의 경로를 찾는 방법 (0) | 2020.11.08 |
ListView 항목 스 와이프 오른쪽에서 왼쪽으로 삭제 버튼 표시 (0) | 2020.11.08 |
ManualResetEvent가 어떤 상태인지 확인하는 방법은 무엇입니까? (0) | 2020.11.08 |