algorithm - STL C++

replace_if()

Declaration

template <class ForwardIterator, class Predicate, class X>
void replace_if(
	ForwardIterator xFirst,
	ForwardIterator xLast,
	Predicate xTest,
	const X& kxrValue
);

Description

This function replaces the entries in the range from "xFirst" up to the entry before "xLast" that satisfy condition of the function "xTest" with "kxrValue."

Header Include

#include <algorithm>

Example

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

bool IsAnX(char cChar) {
	return (cChar == 'X');
}

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>::iterator qIter;
	// Output the vector
	cout << "Original: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Replace 'X' with 'x'
	replace_if(qV.begin(), qV.end(), IsAnX, 'x');

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

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

Output

replace_if() Output
 

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