algorithm - STL C++

transform()

Declaration

template <class InIter, class OutIter, class UnaryFn>
OutIter transform(
	InIter qFirst,
	InIter qLast,
	OutIter qResult,
	UnaryFn qUnaryFn
);

Description

This function applies the transformation function "qUnaryFn" to each of the entries from "qFirst" to the one before "qLast," and outputs the result to the range of entries starting at "qResult." The function returns an iterator to the end of the range of transformed entries. For the overloaded version, we use binary function "qBinaryFn" to transform the the ranges starting at "qFirst1" and "qFirst2."

Header Include

#include <algorithm>

Overloads

template <class InIter1, class InIter2, class OutIter, class BinaryFn>
OutIter transform(
	InIter1 qFirst1,
	InIter1 qLast1,
	InIter2 qFirst2,
	OutIter qResult,
	BinaryFn qBinaryFn
);

Example

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

char ToUpper(char cChar) {
	return (char)(toupper(cChar));
}

int main()
{
	using namespace std;

	// Create two vector instances
	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> qT(10);

	// Transform the original vector
	transform(qV.begin(), qV.end(), qT.begin(), ToUpper);

	// Output the orignal vector and the transformed one
	cout << "Original: ";
	vector<char>::iterator qIter;
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;
	cout << "Tranformed: ";
	for (qIter = qT.begin(); qIter != qT.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

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

Output

transform() Output
 

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