Nice programing

std :: map에 요소가 있는지 확인하는 방법은 무엇입니까?

nicepro 2020. 12. 31. 23:29
반응형

std :: map에 요소가 있는지 확인하는 방법은 무엇입니까?


내 사용 사례 :

map<string, Car> cars;
bool exists(const string& name) {
  // somehow I should find whether my MAP has a car
  // with the name provided
  return false;
} 

C ++로 수행하는 가장 좋고 가장 우아한 방법을 제안 해 주시겠습니까? 감사.


물론입니다. 반복자를 사용하세요.

map<string,Car>::const_iterator it = cars.find(name);
return it!=cars.end();

return cars.find(name) != cars.end();

당신은 또한 사용할 수 있습니다

bool exists(const string& name) {
  return cars.count(name) != 0;
} 

find ()의 iterator-Value에 대한 답변과 .end ()와의 비교 외에도 다른 방법이 있습니다 : map :: count.

특정 키로 map :: count (key)를 호출 할 수 있습니다. 주어진 키에 대해 얼마나 많은 항목이 존재하는지 반환합니다. 고유 키가있는 맵의 경우 결과는 0 또는 1이됩니다. 동일한 인터페이스를 가진 멀티 맵도 존재하므로 안전한쪽에 존재하려면! = 0과 비교하는 것이 좋습니다.

귀하의 예를 들어, 그것은

return (cars.count(name)>0);

내가 본 이점은 1. 더 짧은 코드, 2. 라이브러리가 표현 세부 사항을 사용하여 내부적으로 적용 할 수있는 최적화의 이점입니다.


이건 어떤가요:

template <typename KeyType, typename Collection>
bool exists_in(Collection const& haystack, KeyType const& needle) {
    return std::find(haystack.begin(), haystack.end(), needle) != haystack.end();
}

template <typename K, typename V>
bool exists_in(std::map<K,V> const& haystack, K const& needle) {
    return haystack.find(needle) != haystack.end();
}

이것은 보다 효율적인 검색 대안을 제공 하기 때문에 exists_in를 통해 모든 표준 컨테이너와 함께 작동 std::find하고 특수 버전을 사용합니다 std::map. 필요에 따라 추가 전문화를 추가 할 수 있습니다 (예 : for std::set및 기타).


bool exists(const string& name)
{
    return cars.find(name) != cars.end();
}

std::map::find(const key_type& x );

map::end항목이 존재하지 않으면 반환 됩니다.


bool exists(const std::map<std::string, Car>& cars, const std::string& name) {
  return cars.end() != cars.find(name);
}

C ++ 20 :

return cars.contains(name);

#define itertype(v) typeof((v).begin())
itertype(cars) it = cars.find(name);
return it != cars.end();

참조 URL : https://stackoverflow.com/questions/2781899/how-to-find-whether-an-element-exists-in-stdmap

반응형