为什么在对集合执行 set_union 时需要插入器函数调用? [英] Why do we need an inserter function call when doing a set_union for a set?

查看:30
本文介绍了为什么在对集合执行 set_union 时需要插入器函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要像这样调用 STL 的 set_union 函数:

i need to make the call to the set_union function of STL like this:

set<int> a1, a2;

set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), inserter(a1, a1.begin());

而不是

set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), a1.begin());

为什么会这样?

推荐答案

a1.begin() 根本不是一个输出迭代器.inserter(a1,a1.begin()) 返回一个输出迭代器,它将为每个元素调用集合的插入函数.但我什至不确定第一个版本是否正确.您迭代插入新元素的同一个集合.(!)

a1.begin() is simply not an output iterator. inserter(a1,a1.begin()) returns an output iterator which will invoke the set's insert function for each element. But I'm not even sure whether the first version is even correct. You iterate over the same set you insert new elements into. (!)

既然你已经处理了 set<> 对象,你为什么不简单地写

Since you deal with set<> objects already, why don't you simply write

a1.insert(a2.begin(),a2.end());

?

这篇关于为什么在对集合执行 set_union 时需要插入器函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆