C ++ in brief check if element in STL container (e.g. vector)

bool xInItems = std::find(items.begin(), items.end(), x) != items.end(); 

Is there a shorter way to check if there are x in elements? This seems overly detailed (repeating paragraphs three times), which makes it difficult to read the code.

For example, is there something like the following:

 bool xInItems = boost::contains(items, x); 

If there is no more concise boost / stl algorithm to check if a collection contains an element, is it considered good or bad practice to use a helper function instead to include contains(items, x) ?

Am I using the wrong STL container? Even std :: set will result in bool xInItems = items.find(x) != items.end(); that still seems verbose. Am I thinking about it wrong?

+6
source share
5 answers

If your data is sorted, you can use std::binary_search , which returns bool :

 bool xInItems = std::binary_search(items.begin(), items.end(), x)); 

If you really need to leave the elements un-sorted, but there is C ++ 11, you can use std::any_of , but this requires a predicate, so it will likely be as detailed as possible than std::find (and probably more than that).

+1
source

It's not hard to write a template function from scratch.

 template<typename T, typename Iterator> bool contains(Iterator it1, Iterator it2, const T & value) { return std::find(it1, it2, value) != it2; } template<typename T, typename Container> bool contains(const Container & c, const T & value) { return contains(c.begin(), c.end(), value); } 

You can even provide specializations for containers that have their own find function so that it does not call std::find .

+4
source

any_of_equal will complete the task:

 #include <boost/algorithm/cxx11/any_of.hpp> bool xInItems = boost::algorithm::any_of_equal(items, x); 
+2
source

One easy way to determine if an item is inside a set is:

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

So, if you want to use a set of integers, it could be something like:

 stl::set<int> intSet; intSet.insert(3); if( intSet.find(3) != intSet.end()) printf("Found it!"); 
0
source
 #include "boost/range/algorithm/find.hpp" bool xInItems = boost::find(items, x) != items.end(); 

This will be as brief as you would expect, given the preference for the flexible use of an iterator in C ++.

You should probably just stick to std :: find as it is idiomatic, and hope that eventually std :: range will be accepted and provided with a standard, more concise alternative to iterator pairs.

0
source

Source: https://habr.com/ru/post/976228/


All Articles