2017-06-03 68 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的,所以你将无法更新它们。您可以尝试将指针存储在集合中(并提供适当的间接比较器)。 –