지도에 키 값이 포함되어 있는지 확인 하시겠습니까? Bar b3 = iter->second; } 이것을

STL 맵에 주어진 키의 값이 포함되어 있는지 확인하는 가장 좋은 방법은 무엇입니까?

#include <map>

using namespace std;

struct Bar
{
    int i;
};

int main()
{
    map<int, Bar> m;
    Bar b = {0};
    Bar b1 = {1};

    m[0] = b;
    m[1] = b1;

    //Bar b2 = m[2];
    map<int, Bar>::iterator iter = m.find(2);
    Bar b3 = iter->second;

}

이것을 디버거에서 검사하면 iter가비지 데이터 처럼 보입니다 .

이 줄을 주석 해제하면 :

Bar b2 = m[2]

디버거는이 표시 b2됩니다 {i = 0}. (정의되지 않은 인덱스를 사용하면 모든 비어 있거나 초기화되지 않은 값을 가진 구조체가 반환된다는 것을 의미한다고 생각합니다.)

이 방법들 중 어느 것도 그렇게 훌륭하지 않습니다. 내가 정말로 원하는 것은 다음과 같은 인터페이스입니다.

bool getValue(int key, Bar& out)
{
    if (map contains value for key)
    {
        out = map[key];
        return true;
    }
    return false;
}

이 선들을 따라 뭔가 존재 하는가?



답변

이 선들을 따라 뭔가 존재 하는가?

아니요. stl map 클래스를 사용 ::find()하면 맵을 검색하고 반환 된 반복자와std::map::end()

그래서

map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
   //element found;
   b3 = it->second;
}

분명히 getValue()원하는 경우 (C ++에서도 사용할 이유가 없습니다) 자신의 루틴을 작성할 수 는 out있지만 사용 중단이 생기면 std::map::find()시간을 낭비하고 싶지 않을 것입니다.

또한 코드가 약간 잘못되었습니다.

m.find('2'); 키 값을 찾기 위해지도를 검색합니다. '2' . IIRC C ++ 컴파일러는 ‘2’를 암시 적으로 int로 변환하므로 원하는 ‘2’에 대한 ASCII 코드의 숫자 값이 생성됩니다.

이 예에서 키 유형은 다음 int과 같이 검색하려고합니다.m.find(2);


답변

맵이 멀티 맵이 아닌 한 가장 우아한 방법 중 하나는 count 메소드를 사용하는 것입니다.

if (m.count(key))
    // key exists

요소가 실제로지도에 존재하면 개수는 1입니다.


답변

정확한 구문이 아닌 find만으로 이미 존재합니다.

if (m.find(2) == m.end() )
{
    // key 2 doesn't exist
}

값이 존재하는 경우 값에 액세스하려면 다음을 수행하십시오.

map<int, Bar>::iterator iter = m.find(2);
if (iter != m.end() )
{
    // key 2 exists, do something with iter->second (the value)
}

C ++ 0x 및 auto를 사용하면 구문이 더 간단합니다.

auto iter = m.find(2);
if (iter != m.end() )
{
    // key 2 exists, do something with iter->second (the value)
}

단순화하기 위해 새로운 메커니즘을 고안하는 대신 익숙해 지도록 권장합니다. 약간의 코드를 줄일 수도 있지만 그렇게하는 비용을 고려하십시오. 이제 C ++에 익숙한 사람들이 인식 할 수없는 새로운 기능을 소개했습니다.

이러한 경고에도 불구하고이를 구현하려면 다음을 수행하십시오.

template <class Key, class Value, class Comparator, class Alloc>
bool getValue(const std::map<Key, Value, Comparator, Alloc>& my_map, int key, Value& out)
{
    typename std::map<Key, Value, Comparator, Alloc>::const_iterator it = my_map.find(key);
    if (it != my_map.end() )
    {
        out = it->second;
        return true;
    }
    return false;
}

답변

방금 C ++ 20 을 사용하면

bool std::map::contains( const Key& key ) const;

map이 key가있는 요소를 보유하면 true를 반환합니다 key.


답변

amap.findamap::end찾고있는 것을 찾지 못하면 반환합니다- 그것을 확인해야합니다.


답변

의 반환 값 확인 find에 대한을 end.

map<int, Bar>::iterator it = m.find('2');
if ( m.end() != it ) {
  // contains
  ...
}

답변

다음 코드를 사용하여 getValue 함수를 작성할 수 있습니다.

bool getValue(const std::map<int, Bar>& input, int key, Bar& out)
{
   std::map<int, Bar>::iterator foundIter = input.find(key);
   if (foundIter != input.end())
   {
      out = foundIter->second;
      return true;
   }
   return false;
}