Возможно, закодируйте их в известный набор - что-то как основа 64 является популярным выбором.
Типичный способ проверки наличия во многих контейнерах STL:
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
}
Однако в большинстве случаев мне нужен доступ к элементу везде, где я проверяю за его существование.
Так что мне все равно придется найти итератор. Тогда, конечно, лучше просто сравнить с концом
тоже.
set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
// do something with *it
}
C ++ 20
В C ++ 20 набор получает функцию содержит
, поэтому становится возможным следующее
if (myset.contains(x)) {
// x is in the set
} else {
// no x
}
Чтобы прояснить, причина, по которой в этих типах контейнеров нет такого члена, как contains ()
, заключается в том, что это может привести к написанию неэффективного кода. Такой метод, вероятно, просто сделает this-> find (key)! = This-> end ()
внутренне, но подумайте, что вы делаете, когда ключ действительно присутствует; в большинстве случаев вы затем захотите получить элемент и что-нибудь с ним сделать. Это означает, что вам придется выполнить второй метод find ()
, что неэффективно. Лучше использовать find напрямую, чтобы вы могли кэшировать свой результат, например:
Container::const_iterator it = myContainer.find(key);
if (it != myContainer.end())
{
// Do something with it, no more lookup needed.
}
else
{
// Key was not present.
}
Конечно, если вас не волнует эффективность, вы всегда можете использовать свой собственный, но в этом случае вам, вероятно, не следует использовать C ++ ...;)
Если вы собирались добавить функцию 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 :: begin
и ] std :: 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);
}
}
Напишите свой:
template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
return container.find(elem) != container.end();
}