algorithm - STL C++

copy_if()

Declaration

template <class InputIterator, class OutputIterator, class Predicate>
OutputIterator copy_if(
	InputIterator qFirst,
	InputIterator qLast,
	OutputIterator qDest,
	Predicate qPred
);

Description

This function copies the entries from "qFirst" to the one before "qLast" that satisfy "qPred" to the location specified by "qDest," writing over the entries.

Header Include

#include <algorithm>

Example

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

// Test function
bool LessThanI(char cChar) {
	return (cChar < 'i');
}

int main()
{
	using namespace std;

	// Create a vector instance
	vector<char> qV;
	qV.push_back('X');
	qV.push_back('o');
	qV.push_back('a');
	qV.push_back('X');
	qV.push_back('.');
	qV.push_back('n');
	qV.push_back('e');
	qV.push_back('t');

	vector<char> qCopy;
	qCopy.push_back('*');
	qCopy.push_back('*');
	qCopy.push_back('*');
	qCopy.push_back('*');
	qCopy.push_back('*');
	qCopy.push_back('*');
	qCopy.push_back('*');
	qCopy.push_back('*');

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

	// Output the copy vector before the copy
	cout << "Before the copy:" << endl;
	for (qIter = qCopy.begin(); qIter != qCopy.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Copy elements from the first vector into the second.
	copy_if(qV.begin(), qV.end(), qCopy.begin(), LessThanI);

	// Output the copy vector after the copy
	cout << "After the copy:" << endl;
	for (qIter = qCopy.begin(); qIter != qCopy.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

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

Output

copy_if() Output
 

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