Description: The header 'boost/algorithm/cxx11/partition_copy.hpp'contains the algorithm partition_copy() in C++ boost library. This function copies the elements from the range [first, last) to two different sequence depending on the value returned by the predicate. If the predicate returns 'True' the element is copied to the range beginning at out_true and rest of the elements are copied to the out_false. Syntax: template<typename InputIterator,typename OutputIterator1,typename OutputIterator2,typename UnaryPredicate> BOOST_CXX14_CONSTEXPRstd::pair<OutputIterator1,OutputIterator2> partition_copy(InputIterator,InputIterator,OutputIterator1,OutputIterator2,UnaryPredicate);
template<typename Range,typename OutputIterator1,typename OutputIterator2,typename UnaryPredicate> BOOST_CXX14_CONSTEXPRstd::pair<OutputIterator1,OutputIterator2> partition_copy(constRange&,OutputIterator1,OutputIterator2,UnaryPredicate); 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.) out_true: It specifies the beginning of the output range for the elements that satisfy the predicate 4.) out_false: It specifies the beginning of the output range for the elements that don't satisfy the predicate 3.) UnaryPredicate: It is a unary function that accepts the elements of the sequence in the range provided in argument and returns true or false based on some condition.
The function returns a std::pair constructed from the iterator to the end of the out_true range and the iterator to the end of the out_false range.
intmain() { vector<int> Arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, Arr_True, Arr_False; /* Predicate to check even elements in sequence */ auto predicate = [](int element) { return element % 2 == 0; }; /* Predicate which determine if the element will be stored in Arr_True or Arr_False ** back_inserter generates iterator for inserting element at the end of array */ boost::algorithm::partition_copy(Arr.begin(), Arr.end(), back_inserter(Arr_True), back_inserter(Arr_False), predicate); cout << "Even elements are: "; for(auto i : Arr_True) cout << i << " "; cout << endl << "Odd elements are: "; for(auto i : Arr_False) cout << i << " "; }
Example: Output: Even elements are: 2 4 6 8 10 Odd elements are: 1 3 5 7 9
Complexity:
Time Complexity: The time complexity is linear between first and last element of the sequence. Predicate is called for the same number of time.
Please write on comment section if you find any mistake or for any suggestions.
Comments