function template
<algorithm>
std::is_partitioned
template <class InputIterator, class UnaryPredicate> bool is_partitioned (InputIterator first, InputIterator last, UnaryPredicate pred);
Test whether range is partitioned
Returns true if all the elements in the range [first,last) for which pred returns true precede those for which it returns false.
If the range is empty, the function returns true.
The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
10
11
12
template <class InputIterator, class UnaryPredicate>
bool is_partitioned (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last && pred(*first)) {
++first;
}
while (first!=last) {
if (pred(*first)) return false;
++first;
}
return true;
}
Parameters
- first, last
- Input iterators to the initial and final positions of the sequence. The range used is
[first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
- pred
- Unary function that accepts an element in the range as argument, and returns a value convertible to
bool. The value returned indicates whether the element belongs to the first group (if true, the element is expected before all the elements for which it returns false).
The function shall not modify its argument.
This can either be a function pointer or a function object.
Return value
true if all the elements in the range [first,last) for which pred returns true precede those for which it returns false.
Otherwise it returns false.
If the range is empty, the function returns true.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// is_partitioned example
#include <iostream> // std::cout
#include <algorithm> // std::is_partitioned
#include <array> // std::array
bool IsOdd (int i) { return (i%2)==1; }
int main () {
std::array<int,7> foo {1,2,3,4,5,6,7};
// print contents:
std::cout << "foo:"; for (int& x:foo) std::cout << ' ' << x;
if ( std::is_partitioned(foo.begin(),foo.end(),IsOdd) )
std::cout << " (partitioned)\n";
else
std::cout << " (not partitioned)\n";
// partition array:
std::partition (foo.begin(),foo.end(),IsOdd);
// print contents again:
std::cout << "foo:"; for (int& x:foo) std::cout << ' ' << x;
if ( std::is_partitioned(foo.begin(),foo.end(),IsOdd) )
std::cout << " (partitioned)\n";
else
std::cout << " (not partitioned)\n";
return 0;
}
Possible output:
foo: 1 2 3 4 5 6 7 (not partitioned)
foo: 1 7 3 5 4 6 2 (partitioned)
Complexity
Up to linear in the distance between first and last: Calls pred for each element until a mismatch is found.
Data races
Some (or all) of the objects in the range [first,last) are accessed (once at most).
Exceptions
Throws if either pred or an operation on an iterator throws.
Note that invalid parameters cause undefined behavior.