栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

#include 
#include 
//#include 
#include 
#include 

using namespace std;


int main() {
	set a; // { "1", "3", "3", "4", "4", "5", "6" };
	a.insert("10.0.0.1");
	a.insert("10.0.0.5");
	a.insert("10.0.0.6");
	a.insert("10.0.0.2");
	a.insert("10.0.0.2");
	a.insert("10.0.0.4");
	a.insert("10.0.0.9");

	std::set b; // { "2", "3", "4", "4", "5", "5", "7" };
	b.insert("10.0.0.2");
	b.insert("10.0.0.5");
	b.insert("10.0.0.6");
	b.insert("10.0.0.4");
	b.insert("10.0.0.7");

	cout << "集合a :" << endl;
	for (string iter : a) {
		cout << iter << endl;
	}

	cout << "集合b :" << endl;
	for (string iter : b) {
		cout << iter << endl;
	}

	std::set result;

	//set_difference 需要取差集的两个集合先排序并去掉重复元素。集合初始化后就自动去重排序了
	std::set_difference(a.begin(), a.end(), b.begin(), b.end(),
			inserter(result, result.begin()));

//	std::copy(result.begin(), result.end(),
//			ostream_iterator(std::cout, " "));
	cout << "集合a 和 b 取差集" << endl;
	for (string iter : result) {
		cout << iter << endl;
	}
	return 0;
}

这里需要强调的是在调用set_difference 对两个集合做差集操作前,两个集合一定是去重并且排序了的。这一点很重!不去重或者不排序,都会出现问题。由于set在初始化的时候就已经进行了去重和排序,所以这里没有显示地进行去重排序。如果用vector,则需要我们自己手动添加去重和排序相关代码。详见:

(20条消息) c++ vector<string> 集合做差集_Jerry_liu20080504的专栏-CSDN博客
https://blog.csdn.net/Jerry_liu20080504/article/details/123128417

具体原因:

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
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/744063.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号