algorithm - STL C++

stable_sort()

Declaration

template <class BidirIter>
void stable_sort(
	BidirIter xFirst,
	BidirIter xLast
);

Description

This function sorts the entries in the range starting from "xFirst" up to the entry before "xLast." This is exactly like the sort() function except that entries that are equivalent (or more precisely, not comparable by less than) maintain their original relative order. The overloaded version takes a comparison function, "xComp," and uses that to compare entries instead of less than.

Header Include

#include <algorithm>

Overloads

template <class BidirIter, class Pred>
void stable_sort(
	BidirIter xFirst,
	BidirIter xLast,
	Pred xComp
);

Example

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

int main()
{
	using namespace std;

	// Create a vector with random entries
	vector<int> qV;
	for (int i = 0; i < 10; ++i) {
		qV.push_back(rand() % 20);
	}

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

	// Sort the vector
	stable_sort(qV.begin(), qV.end());

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

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

Output

stable_sort() Output
 

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