2017-04-19 70 views
0

當兩個數組中有共同元素時,std set_union是否總是從第一個數組中獲取這些共同元素?從下面的代碼片斷中可以看出它總是從第一個數組中挑選出共同的元素,但這是有保證的嗎?如何讓它從第二個挑選。does std set_union始終採用第一個共同元素

#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 
+0

[這'的std :: set_union'參考(HTTP://en.cppreference .com/w/cpp/algorithm/set_union)應該會有所幫助。 –

回答

1

是的,它從基準here

兩個集合的並集是由存在於任何一個所述元件形成或者兩者兼而有之。第二個範圍中具有第一個範圍中的等效元素的元素不會複製到結果範圍中。

如果你想讓它從第二(fooB)挑,你換的參數:

std::set_union(fooB, fooB+5, fooA, fooA+5, std::back_inserter(fooUnion), comp); 
相關問題