[c++] 요소가 std :: set에 있는지 확인하는 방법?

요소가 세트에 있는지 어떻게 확인합니까?

다음 코드와 같은 간단한 것이 있습니까?

myset.find(x) != myset.end()



답변

일반적인 방법으로는 다음과 같은 많은 STL 컨테이너에 존재를 확인하기 위해 std::map, std::set…입니다 :

const bool is_in = container.find(element) != container.end();


답변

요소가 존재하는지 간단히 알려주는 또 다른 방법은 count()

if (myset.count(x)) {
   // x is in the set, count is 1
} else {
   // count zero, i.e. x not in the set
}

그러나 대부분의 경우 요소의 존재를 확인하는 곳마다 요소에 액세스해야합니다.

어쨌든 반복자를 찾아야합니다. 그런 다음 물론 간단히 비교하는 것이 좋습니다 end.

set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
   // do something with *it
}

C ++ 20

C ++ 20에서 set은 contains함수를 얻으므로 https://stackoverflow.com/a/54197839/895245

if (myset.contains(x)) {
  // x is in the set
} else {
  // no x 
}


답변

분명히 말하면, contains()이러한 컨테이너 유형 과 같은 멤버가없는 이유는 비효율적 인 코드를 작성할 수 있기 때문입니다. 이러한 방법은 아마도 this->find(key) != this->end()내부적으로 수행 할 것이지만 실제로 키가있을 때 수행하는 작업을 고려하십시오. 대부분의 경우 요소를 가져 와서 무언가를 원할 것입니다. 이것은 당신이 두 번째를해야한다는 것을 의미하며 find(), 이는 비효율적입니다. find를 직접 사용하는 것이 좋으므로 다음과 같이 결과를 캐시 할 수 있습니다.

auto it = myContainer.find(key);
if (it != myContainer.end())
{
    // Do something with it, no more lookup needed.
}
else
{
    // Key was not present.
}

물론 효율성에 신경 쓰지 않는다면 항상 자신 만 롤링 할 수는 있지만 아마도 C ++을 사용해서는 안됩니다 …;)


답변

C ++ 20 에서는 마침내 std::set::contains메소드를 얻게 됩니다.

#include <iostream>
#include <string>
#include <set>

int main()
{
    std::set<std::string> example = {"Do", "not", "panic", "!!!"};

    if(example.contains("panic")) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}


답변

contains함수 를 추가하려는 경우 다음과 같이 보일 수 있습니다.

#include <algorithm>
#include <iterator>

template<class TInputIterator, class T> inline
bool contains(TInputIterator first, TInputIterator last, const T& value)
{
    return std::find(first, last, value) != last;
}

template<class TContainer, class T> inline
bool contains(const TContainer& container, const T& value)
{
    // This works with more containers but requires std::begin and std::end
    // from C++0x, which you can get either:
    //  1. By using a C++0x compiler or
    //  2. Including the utility functions below.
    return contains(std::begin(container), std::end(container), value);

    // This works pre-C++0x (and without the utility functions below, but doesn't
    // work for fixed-length arrays.
    //return contains(container.begin(), container.end(), value);
}

template<class T> inline
bool contains(const std::set<T>& container, const T& value)
{
    return container.find(value) != container.end();
}

이것은 std::set다른 STL 컨테이너 및 고정 길이 배열에서도 작동 합니다.

void test()
{
    std::set<int> set;
    set.insert(1);
    set.insert(4);
    assert(!contains(set, 3));

    int set2[] = { 1, 2, 3 };
    assert(contains(set2, 3));
}

편집하다:

주석에서 지적했듯이 C ++ 0x ( std::beginstd::end)에 새로운 기능을 실수로 사용했습니다 . VS2010의 사소한 구현은 다음과 같습니다.

namespace std {

template<class _Container> inline
    typename _Container::iterator begin(_Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::const_iterator begin(const _Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::iterator end(_Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Container> inline
    typename _Container::const_iterator end(const _Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *begin(_Ty (&_Array)[_Size])
    { // get beginning of array
    return (&_Array[0]);
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *end(_Ty (&_Array)[_Size])
    { // get end of array
    return (&_Array[0] + _Size);
    }

}


답변

요소를 삽입하는 동안 요소가 설정되어 있는지 여부를 확인할 수도 있습니다. 단일 요소 버전은 멤버 pair :: first가 새로 삽입 된 요소 또는 세트에 이미있는 동등한 요소를 가리키는 반복자로 설정된 쌍을 리턴합니다. 새 요소가 삽입 된 경우 쌍의 pair :: second 요소는 true로 설정되고 동등한 요소가 이미 존재하면 false로 설정됩니다.

예를 들어, 세트에 이미 요소로 20이 있다고 가정하십시오.

 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;

 ret=myset.insert(20);
 if(ret.second==false)
 {
     //do nothing

 }
 else
 {
    //do something
 }

 it=ret.first //points to element 20 already in set.

요소가 pair :: first보다 새로 삽입 된 경우 set에서 새 요소의 위치를 ​​가리 킵니다.


답변

직접 작성하십시오 :

template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
  return container.find(elem) != container.end();
}