2015-08-16 41 views
0

什麼是最有效的方法來創建一個從2集包含它們兩個值的子集?任何C++ STL庫可以用來解決這個(不Boost庫如果可能的話):如何找到2組的交集?

Set A = {2, 3, 5, 7, 11, ...} 
Set B = {1, 3, 5, 7, 9, 11, ...} 

Subset should be = {3, 5, 7, 11, ...} 
+0

你已經看過'std :: set'了嗎? –

+1

@ bigotHER的答案是正確的,但是這個問題是一個「如何」的問題或算法問題? (如果它是算法的,並且集合是有序的,那麼http://stackoverflow.com/questions/5958169/how-to-merge-two-sorted-arrays-into-a-sorted-array)。 –

回答

3

您可以通過使用set_intersection做到這一點,你會發現一個例子還有如何使用它:

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 
int main() 
{ 
    std::vector<int> v1{2, 3, 5, 7, 11};; 
    std::vector<int> v2{1, 3, 5, 7, 9, 11}; 
    std::sort(v1.begin(), v1.end()); 
    std::sort(v2.begin(), v2.end()); 

    std::vector<int> v_intersection; 

    std::set_intersection(v1.begin(), v1.end(), 
          v2.begin(), v2.end(), 
          std::back_inserter(v_intersection)); 
    for(int n : v_intersection) 
     std::cout << n << ' '; 
} 

結果將是:

3 5 7 11 
+0

至少鏈接更好[參考](http://en.cppreference.com/w/cpp/algorithm/set_intersection)。 – LogicStuff

+0

@LogicStuff更新了,謝謝 –

+0

@bigotHER我的意思是主要是因爲更清晰的例子。 – LogicStuff

1

使用std::set_intersection如下所述:

http://www.cplusplus.com/reference/algorithm/set_intersection/

+2

查找C++文檔時,我更喜歡[cppreference.com](http://en.cppreference.com/w/cpp)到[www.cplusplus.com](http:// www。因爲第一個比後者更正確。 –

+0

謝謝,我會記住這一點。 –