[英]c++ STL set difference
C++ STL集合數據結構有集合差分算子嗎?
是的,它在<algorithm>
並被稱為: std::set_difference
。 用法是:
#include <algorithm>
#include <set>
#include <iterator>
// ...
std::set<int> s1, s2;
// Fill in s1 and s2 with values
std::set<int> result;
std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(result, result.end()));
最后,設置result
將包含s1-s2
。
是的,算法標題中有一個set_difference函數。
編輯:
僅供參考,設置數據結構能夠有效地使用該算法,如其文檔中所述 。 該算法不僅可以在集合上工作,還可以在排序集合上的任何迭代器對上工作。
正如其他人所提到的,這是一種外部算法,而不是一種方法。 據推測,這對您的應用程序來說很好。
在語言意義上不是“運算符”,但標准庫中有set_difference算法:
http://www.cplusplus.com/reference/algorithm/set_difference.html
當然,其他基本集合操作也存在 - (聯合等),如鏈接文章末尾的“另請參閱”部分所示。
選擇的答案是正確的,但有一些語法錯誤。
代替
#include <algorithms>
使用
#include <algorithm>
代替
std::insert_iterator(result, result.end()));
使用
std::insert_iterator<set<int> >(result, result.end()));
再一次,促進救援:
#include <string>
#include <set>
#include <boost/range/algorithm/set_algorithm.hpp>
std::set<std::string> set0, set1, setDifference;
boost::set_difference(set0, set1, std::inserter(setDifference, setDifference.begin());
setDifference將包含set0-set1。
不是一種方法,而是外部算法函數set_difference
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
顯然,確實如此。
C ++沒有定義集合差異運算符,但您可以定義自己的(使用其他響應中給出的代碼):
template<class T>
set<T> operator -(set<T> reference, set<T> items_to_remove)
{
set<T> result;
std::set_difference(
reference.begin(), reference.end(),
items_to_remove.begin(), items_to_remove.end(),
std::inserter(result, result.end()));
return result;
}
我在這里看到的所有答案都是O(n)。 這不會更好嗎?:
template <class Key, class Compare, class Allocator>
std::set<Key, Compare, Allocator>
set_subtract(std::set<Key, Compare, Allocator>&& lhs,
const std::set<Key, Compare, Allocator>& rhs) {
if (lhs.empty()) { return lhs; }
// First narrow down the overlapping range:
const auto rhsbeg = rhs.lower_bound(*lhs.begin());
const auto rhsend = rhs.upper_bound(*lhs.rbegin());
for (auto i = rhsbeg; i != rhsend; ++i) {
lhs.erase(*i);
}
return std::move(lhs);
}
這似乎做對了。 我不知道如何處理Compare
的類型沒有完全指定其行為的情況,如果Compare
是std::function<bool(int,int)>
,但除此之外,這似乎工作正常,應該像O((num lhs.size()
)•log( lhs.size()
))。
在lhs
不包含*i
的情況下,可能可以通過執行O(log( rhs.size()
))搜索rhs
的下一個元素來進一步優化,該元素是> = lhs
的下一個元素。 這將優化lhs = {0, 1000}
和rhs = {1, 2, ..., 999}
以在對數時間中進行減法。
我們可以使用嗎?
set_difference(set1.begin(), set1.end(), set2.begin(). set2,end(),std::back_inserter(result)).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.