algorithm - STL C++

set_difference()

Declaration

template <class InIter1, class InIter2, class OutIter>
OutIter set_difference(
	InIter1 xFirst1,
	InIter1 xLast1,
	InIter2 xFirst2,
	InIter2 xLast2,
	OutIter xResult
);

Description

This function finds the setwise difference between the ordered of entries in the range starting from "xFirst1" up to the entry before "xLast1" and the ordered of entries in the range starting from "xFirst2" up to the entry before "xLast2." The function stores the difference in the entries starting at "xResult" and continues up through entry before the return value. Note that the entries in each range must be sorted and sufficient storage must exist at "xResult" to fit the difference. Also, the ranges may contain multiple copies of the same entry, which is not a set in the mathematical sense of the word. The overloaded version takes a comparison function, "xComp," and uses that to order entries instead of the less than.

Header Include

#include <algorithm>

Overloads

template <class InIter1, class InIter2, class OutIter, class Pred>
OutIter set_difference(
	InIter1 xFirst1,
	InIter1 xLast1,
	InIter2 xFirst2,
	InIter2 xLast2,
	OutIter xResult,
	Pred xComp
);

Example

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

int main()
{
	using namespace std;

	// Create two sorted vector instances
	vector<int> qSet1;
	qSet1.push_back(3);
	qSet1.push_back(5);
	qSet1.push_back(5);
	qSet1.push_back(5);
	qSet1.push_back(6);
	qSet1.push_back(9);
	qSet1.push_back(11);

	vector<int> qSet2;
	qSet2.push_back(2);
	qSet2.push_back(3);
	qSet2.push_back(5);
	qSet2.push_back(5);
	qSet2.push_back(7);
	qSet2.push_back(8);

	// Create a third vector for the result
	vector<int> qDiff(10);

	// Output set 1 and set 2
	vector<int>::iterator qIter;
	cout << "Set 1: ";
	for (qIter = qSet1.begin(); qIter != qSet1.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	cout << "Set 2: ";
	for (qIter = qSet2.begin(); qIter != qSet2.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	// Take the setwise difference
	vector<int>::iterator qResult;
	qResult = set_difference(qSet1.begin(), qSet1.end(),
		qSet2.begin(), qSet2.end(), qDiff.begin());

	// Output the setwise difference
	cout << "Diff : ";
	for (qIter = qDiff.begin(); qIter != qResult; ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

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

Output

set_difference() Output
 

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