2017-06-03 67 views
0

2個矢量我已經2個矢量,即deals_allFXDealdeals_new,其中FxDeal是一類合併使用STL算法

struct FxDeal 
{ 
    int deal_id_; // primary key 
    string ccy_pair_; 
    double amount_; 
} 

兩個矢量由主鍵字段deal_id_排序。

我怎麼能合併deals_new成也出現在deal_newdeals_alldeals_all使得deals_new

  • 新的交易被複制或附加到deals_all,並
  • 交易(按主鍵 deal_id_)將有字段ccy_pair_amount_已更新

我正在使用C++ 11。

+0

矢量的排序?您是否有任何訂單要求,即對'deals_all'中元素序列的任何要求? – Arun

+0

哦,它是排序,讓我更新的問題。 – athos

回答

3

您可以使用std::set_union。 (這裏假定向量是使用名爲compare_by_id的比較函數進行排序的,其名稱的含義如此)。

std::vector<FxDeal> merged_deals; 
std::set_union(deals_new.begin(), deals_new.end(), 
    deals_all.begin(), deals_all.end(), 
    std::back_inserter(merged_deals), 
    compare_by_id); 

deals_all = std::move(merged_deals); 

確保你傳遞deals_new作爲第一個範圍,因爲這將是它在重複的ID的情況下複製了一個。

+0

'compare_by_id'我想是一個Lambda? – athos

+0

要求「deal_all中的交易也出現在deal_new中(通過主鍵deal_id_),將有字段ccy_pair_和amount_ updated」處理嗎? – Arun

+1

@athos:如果你願意的話,它可能是一個lambda。或者是一個命名的函數對象類或函數的對象。 –

2

我會嘗試以下(僞代碼):

std::set<FxDeal> deal_set{deals_all.cbegin(), deals_all.cend()}; 

for (auto const& d : deals_new) { 
    auto it = deal_set.find(d); 
    if (it != deal_set.end()) { 
    FxDeal x = *it; 
    // update x with d.ccy_pair_ and d.amount_; 
    // this allows adding amounts, for e.g. x.amount_ += d.amount_ 
    deal_set.erase(it); 
    deal_set.insert(x);   
    } 
    else { 
    deal_set.insert(d); 
    } 
} 

deals_all.assign(deal_set.cbegin(), deal_set.cend()); 
+0

所以沒有像std :: for_each,std :: transform等算法讓生活更輕鬆?有 – athos

+0

有。雖然我不能在這個答案中使用它們。我已經更新了答案,請現在檢查。 – Arun

+0

'std :: set'的元素是const的,所以你將無法更新它們。您可以嘗試將指針存儲在集合中(並提供適當的間接比較器)。 –