algorithm - STL C++

partition()

Declaration

template <class BidirIter, class Predicate>
BidirIter partition(
	BidirIter xFirst,
	BidirIter xLast,
	Predicate xTest
);

Description

This function uses the function "xTest" to order the elements in range from "xFirst" up through the one before "xLast" into two sets so that each element in the first set returns true when passed into "xTest" while each element in the second set returns false.

Header Include

#include <algorithm>

Example

#include <iostream>
#include <vector>
#include <algorithm>

bool IsEven(int iInt) {
	return ((iInt % 2) == 0);
}

int main()
{
	using namespace std;

	// Create two vector instances
	vector<int> qV;
	for (int i = 0; i < 30; i += 3) {
		qV.push_back(30-i);
	}

	vector<int>::iterator qIter;
	// Output the vector
	cout << "The Vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	vector<int>::iterator qOddIter;
	// Partition the vector into even and odd ints
	qOddIter = partition(qV.begin(), qV.end(), IsEven);

	// Output the partitioned vector
	cout << "Partitioned: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		if (qIter == qOddIter) {
			cout << "|  ";
		}
		cout << *qIter << "  ";
	}
	cout << endl;

	// Keep the window open
	cin.get();
	return 0;
}

Output

partition() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.