我有两个向量,即deals_all
和deals_new
of FXDeal
,其中FxDeal
是一个类
struct FxDeal
{
int deal_id_; // primary key
string ccy_pair_;
double amount_;
}
两个向量都按照主键字段deal_id_
进行排序。
我如何将deals_new
合并到deals_all
中以便
deals_new
中的新交易被复制或附加到deals_all
中,并且deals_all
中也出现在deal_new
中的交易(按主键deal_id_
),将更新字段ccy_pair_
和amount_
我在用c++11。
发布于 2017-06-03 15:15:31
您可以使用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
作为第一个范围传递,因为在重复ids的情况下,这将是复制的范围。
发布于 2017-06-03 15:08:36
我将尝试以下(伪代码):
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());
https://stackoverflow.com/questions/44345259
复制相似问题