Add trivial wxVectorContains() helper

This is nicer than using std::find() when only a test for presence is
required.
This commit is contained in:
Vadim Zeitlin
2020-11-16 04:04:12 +01:00
parent b021c3c938
commit 516066939a
3 changed files with 42 additions and 0 deletions

View File

@@ -26,6 +26,12 @@ inline void wxVectorSort(wxVector<T>& v)
std::sort(v.begin(), v.end());
}
template<typename T>
inline bool wxVectorContains(const wxVector<T>& v, const T& obj)
{
return std::find(v.begin(), v.end(), obj) != v.end();
}
#else // !wxUSE_STD_CONTAINERS
#include "wx/scopeguard.h"
@@ -688,7 +694,17 @@ void wxVectorSort(wxVector<T>& v)
wxPrivate::wxVectorComparator<T>::Compare, NULL);
}
template<typename T>
inline bool wxVectorContains(const wxVector<T>& v, const T& obj)
{
for ( size_t n = 0; n < v.size(); ++n )
{
if ( v[n] == obj )
return true;
}
return false;
}
#endif // wxUSE_STD_CONTAINERS/!wxUSE_STD_CONTAINERS

View File

@@ -307,3 +307,13 @@ public:
*/
template<typename T>
void wxVectorSort(wxVector<T>& v);
/**
Returns true if the vector contains the given value.
This is just a trivial wrapper around std::find().
@since 3.1.5
*/
template<typename T>
bool wxVectorContains(const wxVector<T>& v, const T& value);

View File

@@ -288,6 +288,22 @@ TEST_CASE("wxVector::Sort", "[vector][sort]")
}
}
TEST_CASE("wxVector::Contains", "[vector][contains]")
{
wxVector<int> v;
CHECK( !wxVectorContains(v, 0) );
v.push_back(3);
CHECK( wxVectorContains(v, 3) );
v.push_back(2);
v.push_back(3);
CHECK( wxVectorContains(v, 2) );
CHECK( wxVectorContains(v, 3) );
CHECK( !wxVectorContains(v, 1) );
}
TEST_CASE("wxVector::operator==", "[vector][compare]")
{
wxVector<wxString> v1, v2;