要素がセット内にあることをどのように確認しますか?
次のコードに相当する単純なものはありますか。
myset.find(x) != myset.end()
std::map
、std::set
、 ...などの多くの 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
}
しかし、ほとんどの場合、要素の存在を確認するたびに、その要素にアクセスする必要があることに気付きます。
したがって、とにかくイテレータを見つける必要があります。もちろん、単純に比較する方が良いでしょう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()
これは、非効率的である 2 番目の を実行する必要があることを意味します。次のように結果をキャッシュできるように、 find を直接使用することをお勧めします。
auto 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);
}
}
との一般的なcontains
関数を書くことができました。std::list
std::vector
template<typename T>
bool contains( const list<T>& container, const T& elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
template<typename T>
bool contains( const vector<T>& container, const T& elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
// use:
if( contains( yourList, itemInList ) ) // then do something
これにより、構文が少しクリーンアップされます。
しかし、テンプレート テンプレート パラメーター マジックを使用して、これを任意の stl コンテナーで機能させることはできませんでした。
// NOT WORKING:
template<template<class> class STLContainer, class T>
bool contains( STLContainer<T> container, T elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
最後の回答を改善することについてのコメントはいいでしょう。
あなた自身を書いてください:
template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
return container.find(elem) != container.end();
}
//一般的な構文
set<int>::iterator ii = find(set1.begin(),set1.end(),"element to be searched");
/* 以下のコードでは、存在するかどうかにかかわらず、要素 4 と int セットを見つけようとしています */
set<int>::iterator ii = find(set1.begin(),set1.end(),4);
if(ii!=set1.end())
{
cout<<"element found";
set1.erase(ii);// in case you want to erase that element from set.
}