algorithm - STL C++

swap_ranges()

Declaration

template <class FwdIter1, class FwdIter2>
FwdIter2 swap_ranges(
	FwdIter1 xFirst1,
	FwdIter1 xLast1,
	FwdIter2 xFirst2
);

Description

This function swap the entries that are in the range from "xFirst1" up to the entry before "xLast1" with an equivalent number of entries starting at "xFirst2." The function returns an iterator that points to the end of the second range.

Header Include

#include <algorithm>

Example

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

int main()
{
	using namespace std;

	// Create two vector instances
	vector<char> qV1;
	qV1.push_back('X');
	qV1.push_back('o');
	qV1.push_back('a');
	qV1.push_back('X');
	qV1.push_back('.');
	qV1.push_back('n');
	qV1.push_back('e');
	qV1.push_back('t');

	vector<char> qV2;
	qV2.push_back('C');
	qV2.push_back('+');
	qV2.push_back('+');

	vector<char>::iterator qIter;
	// Output the vectors
	cout << "V1: ";
	for (qIter = qV1.begin(); qIter != qV1.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;
	cout << "V2: ";
	for (qIter = qV2.begin(); qIter != qV2.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	cout << "Swap ranges" << endl;
	// Swap ranges of entries in each vector
	swap_ranges(qV1.begin() + 4, qV1.begin() + 6, qV2.begin() + 1);

	// Output the vectors after the swap
	cout << "V1: ";
	for (qIter = qV1.begin(); qIter != qV1.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;
	cout << "V2: ";
	for (qIter = qV2.begin(); qIter != qV2.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

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

Output

swap_ranges() Output
 

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