Description: The header 'boost/algorithm/cxx11/one_of.hpp'contains the algorithm one_of() in C++ boost library. This function tests if one and only one of the element in the range returns 'true' for some unary function. The unary function accepts each and every array elements individually and returns a Boolean value. The function also returns 'false' if the sequence is empty.
Syntax: template <class InputIterator, class UnaryPredicate> bool one_of(InputIterator first, InputIterator last, UnaryPredicate pred);
Parameters: The following parameters are accepted by the function: 1.) first: It specifies the initial position of the sequence by input iterator (first is inclusive in range). 2.) last: It specifies the end position of the sequence by input iterator (last is exclusive in range). 3.) pred: It is a unary function that accepts the elements of the sequence in the range provided in argument. It returns a Boolean value where true indicates exactly one of the element in sequence have same property to that of the predicate.
The function returns true if one and only one element of the sequence returns true for the predicate else it returns false.
intmain() { int n; cout << "Enter array size: "; cin >> n; cout << "Enter n elements: "; vector<int> A(n); for(int i = 0; i < n; i++) cin >> A[i];
/* predicate which checks if exactly one * element of the sequence is equal to 5. */ auto predicate = [](char element) { return element == 5; }; bool res1 = boost::algorithm::one_of(A.begin(), A.begin()+n, predicate); //for the range [0, n) //bool res2 = boost::algorithm::one_of(A, predicate); //for entire array
if(res1) cout << "Exactly one element is equal to 5"; else cout << "Exactly one element is not equal to 5";
return0; } Example: 1.) Enter array size: 5 Enter n elements: 1 2 3 4 5 Output: Exactly one element is equal to 5 2.) Enter array size: 5 Enter n elements: 5 1 2 5 4 Output: Exactly one element is not equal to 5
Complexity:
Time Complexity: The time complexity is linear between the first and last elements. Predicate is called for the same number of time.
Please write on comment section if you find any mistake or for any suggestions.
Comments