I searched the site and other sources for information about working with the any_of algorithm, but it is very small.
- oneWhat specifically is not clear from the description and example ? - Grundy
- How to set the condition of the range - Vladimir Samofal
- what condition and what range? - Grundy
- std :: array <int, 7> foo = {0,1, -1,3, -3,5, -5}; if (std :: any_of (foo.begin (), foo.end (), [] (int i) {return i <0;})) - Vladimir Samofal
- This is an example of the link above, what do you mean by condition and range? - Grundy
|
1 answer
Well, semantics - "there is at least one such element, that". And the syntax is the transfer of a range (where we check the existence of an element) and a predicate (which element of existence it is).
For example, checking whether there is an even number among the numbers in the vector:
void even_check(const std::vector<int>& v) { if (std::any_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; })) { std::cout << "Четное число есть\n"; } else { std::cout << "Все числа нечетны\n"; } } int main() { std::vector<int> v{1,3,5,7,9}; even_check(v); v.push_back(10); even_check(v); } Well, just in case (all of a sudden you wanted to hear it): the range is transmitted as two iterators. There is no syntactic sugar in the spirit of a range cycle. You can write your own version for the entire container, such as
template<typename Container, typename Pred> bool any_in(const Container c, Pred p) { return any_of(cbegin(c),cend(c),p); } void even_check(std::vector<int>& v) { if (any_in(v, [](int i){ return i % 2 == 0; })) { std::cout << "Четное число есть\n"; } else { std::cout << "Все числа нечетны\n"; } } |