athos
athos

Reputation: 6405

merge 2 vectors using STL algorithm

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

I'm using c++11.

Upvotes: 0

Views: 124

Answers (2)

Arun
Arun

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

Benjamin Lindley
Benjamin Lindley

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

Related Questions