簡體   English   中英

C ++庫方法用於兩個unordered_set的交集

[英]C++ library method for intersection of two unordered_set

我有兩個unordered_set並想要它們的交集。 我找不到一個庫函數來做到這一點。

基本上,我想要的是這樣的:

unordered_set<int> a = {1, 2, 3};
unordered_set<int> b = {2, 4, 1};

unordered_set<int> c = a.intersect(b); // Should be {1, 2}

我可以做點什么

unordered_set<int> c;
for (int element : a) {
  if (b.count(element) > 0) {
    c.insert(element);
  }
}

但我認為應該有更方便的方法嗎? 如果沒有,有人可以解釋原因嗎? 我知道有set_intersection,但這似乎僅適用於矢量?

謝謝

事實上,基於循環的解決方案是您可以使用std::unordered_set的最佳選擇。

有一個名為std::set_intersection的算法,它允許查找兩個有序范圍的交集:

構造一個從d_first開始的排序范圍,該排序范圍由在排序范圍 [first1,last1]和[first2,last2)中找到的元素組成。

在處理std::unordered_set ,您無法應用此算法,因為std::unordered_set的元素沒有保證順序。

我的建議是堅持使用循環,因為它明確地說明了你想要實現的東西,並且具有線性復雜度( O(N) ,其中N是你用for循環遍歷的無序集合中的元素數量),這是最好的復雜性你可能會實現。

std有一個名為set_intersection的函數。 但是,使用std::set作為輸入參數會有很高的復雜性。更好的解決方案是,從這些集合中創建兩個向量,並使用帶向量的set_intersection作為輸入參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM