假設我有兩個std::set<std::string>
s。第一個old_options
需要與new_options
中包含的其他選項合併。我不能僅僅使用std::merge
(嗯,我這樣做,但不僅如此),因爲我也檢查雙打,並相應地提醒用戶。爲此,我有賦值vs std :: swap和合並並保留重複項在單獨對象中
void merge_options(set<string> &old_options, const set<string> &new_options)
{
// find duplicates and create merged_options, a stringset containing the merged options
// handle duplicated the way I want to
// ...
old_options = merged_options;
}
是它更好地使用
std::swap(merged_options, old_options);
或我的任務?
有沒有更好的方式來過濾重複和合並後返回
set
比連續通話std::set_intersection
和std::set_union
檢測愚弄和合並set
S'我知道它比一次遍歷要慢,並且同時做兩次,但這些集很小(性能不重要),我相信標準比我更信任自己。
簡單,是的,但在性能上並不相同(如果你忽略了因素2,這在大O中應該不重要)。我想到了一個同步遍歷,它基本上是O(log(max(M,N))。這確實會獲得性能,但正如Jerry所說,這更復雜,也許在這裏沒有用處。我不想錯過一個C++庫函數 – rubenvb 2011-03-06 16:34:05
@rubenvb:我認爲同時遍歷將是O(max(m,n))。它和你的版本的區別在於:1)分配和拷貝更少(假設C++ 03)和2)我認爲我更清楚。我不認爲標準庫有這樣做的更短的方式,但我必須承認''讓我感到驚訝。 –
2011-03-06 16:40:32
是的,'日誌'是二進制搜索,愚蠢的我'= s'。 @Blastfurnace也有不錯的一個。 (和''一直讓我感到驚訝,因此問題) –
rubenvb
2011-03-07 10:32:21