std::is_partitioned用於查找range [first,last)是否已分區。如果條件評估為“真”的所有元素都在條件為“假”的那些元素之前,則可以說範圍是相對於條件進行分區的。
它在頭文件中定義。如果我們要檢查分區範圍是否為空,則此函數返回true。句法:
bool is_partitioned (InputIterator first, InputIterator last, UnaryPredicate pred); first:Input iterator to the first element in the range. last:Input iterator to the last element in the range. 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. 返回: It returns 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.
// C++ program to demonstrate the use of std::is_partitioned
#include <iostream>
#include <algorithm>
#include <vector>
// Defining the BinaryFunction
bool pred(int a)
{
return (a % 3 == 0);
}
using namespace std;
int main()
{
// Declaring first vector
vector<int> v1 = { 3, 6, 9, 10, 11, 13 };
// Using std::is_partitioned
bool b = std::is_partitioned(v1.begin(), v1.end(), pred);
if (b == 1) {
cout << "It is partitioned";
} else {
cout << "It is not partitioned.";
}
return 0;
}
輸出:
It is partitioned
說明:這裏,在此程序中,我們首先將元素存儲在向量中,然後檢查是否所有被3整除的元素都在未被3整除的元素之前存在。因為,對於被攝對象,此條件的值為true向量,因此此函數在分區時在此處返回1。
Another Example
-
檢查是否對所有奇數和偶數元素進行了分區
// C++ program to demonstrate the use of std::is_partitioned #include <iostream> #include <algorithm> #include <vector> // Defining the BinaryFunction bool pred(int a) { return (a % 2 == 0); } using namespace std; int main() { // Declaring first vector vector<int> v1 = { 2, 4, 6, 3, 5, 7, 9 }; // Using std::is_partitioned bool b = std::is_partitioned(v1.begin(), v1.end(), pred); if (b == 1) { cout << "All the even no. are present before odd no."; } else { cout << "All the even no. are not present before odd no."; } // Inserting an even no. at the end of v1 // so std::is_partitioned returns false v1.push_back(16); // Now again using std::is_partitioned b = std::is_partitioned(v1.begin(), v1.end(), pred); if (b == 1) { cout << "\nAll the even no. are present before odd no."; } else { cout << "\nAll the even no. are not present before odd no."; } return 0; }
輸出:
All the even no. are present before odd no. All the even no. are not present before odd no.
相關用法
注:本文由純淨天空篩選整理自 std::is_partitioned in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。