Reputation: 6405
I've 2 vectors, namely deals_all
and deals_new
of FXDeal
, where FxDeal
is a class
struct FxDeal
{
int deal_id_; // primary key
string ccy_pair_;
double amount_;
}
Both vectors are sorted by the primary key field deal_id_
.
How could I merge deals_new
into deals_all
so that
deals_new
are copied or appended to deals_all
, anddeals_all
that appear also in deal_new
(by primary key
deal_id_
), will have field ccy_pair_
and amount_
updatedI'm using c++11.
Upvotes: 0
Views: 124
Reputation: 20383
I would try the following (pseudo-code):
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());
Upvotes: 2
Reputation: 103703
You can use std::set_union
. (this assumes the vectors are sorted using a comparison function called compare_by_id
, which does what the name implies).
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);
Be sure you pass deals_new
as the first range, because that will be the one which is copied over in cases of duplicate ids.
Upvotes: 3