gpt4 book ai didi

c++ - std set_union 是否总是从第一个开始获取公共(public)元素

转载 作者:行者123 更新时间:2023-11-28 05:11:00 27 4
gpt4 key购买 nike

当两个数组中有公共(public)元素时,std set_union 是否总是从第一个数组中取出那些公共(public)元素?从下面的代码片段可以看出,它总是从第一个数组中选取共同的元素,但这是有保证的吗?如何让它从第二个开始挑选。

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

struct Foo
{
Foo(int i, const std::string& n): id(i), name(n){}
int id;
std::string name;
};

bool comp(const Foo& first, const Foo& second)
{
return first.id < second.id;
}

int main()
{
Foo foo5A(5, "A");
Foo foo10A(10, "A");
Foo foo15A(15, "A");
Foo foo20A(20, "A");
Foo foo25A(25, "A");
Foo fooA[] = {foo5A, foo10A, foo15A, foo20A, foo25A};

Foo foo10B(10, "B");
Foo foo20B(20, "B");
Foo foo30B(30, "B");
Foo foo40B(40, "B");
Foo foo50B(50, "B");
Foo fooB[] = {foo10B, foo20B, foo30B, foo40B, foo50B};

std::vector<Foo> fooUnion;
std::set_union(fooA, fooA+5, fooB, fooB+5, std::back_inserter(fooUnion), comp);

for(const auto& f : fooUnion)
{
std::cout << f.id << ":" << f.name << std::endl;
}
}

输出是:

5:A
10:A
15:A
20:A
25:A
30:B
40:B
50:B

最佳答案

是的,确实如此,来自引用文献 here :

The union of two sets is formed by the elements that are present in either one of the sets, or in both. Elements from the second range that have an equivalent element in the first range are not copied to the resulting range.

如果您希望它从第二个 (fooB) 中选择,您可以交换参数:

std::set_union(fooB, fooB+5, fooA, fooA+5, std::back_inserter(fooUnion), comp);

关于c++ - std set_union 是否总是从第一个开始获取公共(public)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43499806/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com