c++ vector<string> 集合做差集

#include <vector>
#include <set>
#include <iostream>
//#include <iterator>
#include <algorithm>

using namespace std;
/**
 * 参考:
 * (20条消息) C++拾取——stl标准库中集合交集、并集、差集、对称差方法_方亮的专栏-CSDN博客_c++ 取交集
 * https://blog.csdn.net/breaksoftware/article/details/88932820
 */

int main() {
	vector<string> a;
	a.push_back("10.0.0.1");
	a.push_back("10.0.0.5");
	a.push_back("10.0.0.6");
	a.push_back("10.0.0.2");
	a.push_back("10.0.0.2"); //注意有重复元素
	a.push_back("10.0.0.4");
	a.push_back("10.0.0.9");

	std::vector<string> b;
	b.push_back("10.0.0.2");
	b.push_back("10.0.0.5");
	b.push_back("10.0.0.6");
	b.push_back("10.0.0.4");
	b.push_back("10.0.0.7");

	//去掉重复元素
	set<string> sa(a.begin(), a.end());
	a.clear();
	a.resize(sa.size());
	a.assign(sa.begin(), sa.end());
	cout << "集合a 内元素去重后:" << endl;
	for (string iter : a) {
		cout << iter << endl;
	}

	//去掉重复元素
	set<string> sb(b.begin(), b.end());
	b.clear();
	b.resize(sb.size());
	b.assign(sb.begin(), sb.end());
	cout << "集合b 内元素去重后:" << endl;
	for (string iter : b) {
		cout << iter << endl;
	}

//	std::sort(a.begin(), a.end()); //如果没排序的话需要排序
//	std::sort(b.begin(), b.end()); //如果没排序的话需要排序
//	cout << "集合a 内元素排序后:" << endl;
//	for (string iter : a) {
//		cout << iter << endl;
//	}

//	cout << "集合b 内元素排序后:" << endl;
//	for (string iter : b) {
//		cout << iter << endl;
//	}

	std::vector<string> result;

	/*求两个集合的差集去重和排序不能少
	 *原因:Equivalent elements are treated individually, that is, if some element is found m times in [first1, last1) and n times in [first2, last2), it will be copied to d_first exactly std::max(m-n, 0) times. The resulting range cannot overlap with either of the input ranges.
	 */
	std::set_difference(a.begin(), a.end(), b.begin(), b.end(),
			std::back_inserter(result)); //差集求的是排序后的两个集合,所以求差集前一定要对两个集合进行排序,否则可能出错。

	cout << "集合a 和 b 取差集" << endl;
	for (string iter : result) {
		cout << iter << endl;
	}
	return 0;
}

这里需要强调的是在调用set_difference 对两个集合做差集操作前,两个集合一定是去重并且排序了的。这一点很重!不去重或者不排序,都会出现问题。

具体原因:

Equivalent elements are treated individually, that is, if some element is found m times in [first1, last1) and n times in [first2, last2), it will be copied to d_first exactly std::max(m-n, 0) times. The resulting range cannot overlap with either of the input ranges.

参考并感谢以下链接:

(20条消息) C++拾取——stl标准库中集合交集、并集、差集、对称差方法_方亮的专栏-CSDN博客_c++ 取交集
https://blog.csdn.net/breaksoftware/article/details/88932820

猜你喜欢

转载自blog.csdn.net/Jerry_liu20080504/article/details/123128417