Mr Z Mr Z - 3 months ago 8
C++ Question

Joining two containers of objects, adding elements if already present

I have two containers of objects of type:

struct Element
{
int A;
int B;

Element operator+=(const Element& rhs)
{
if(A != rhs.A)
throw std::runtime_error("Not like this");

B += rhs.B;
return *this;
}
};

inline Element operator+(Element lhs, const Element& rhs)
{
lhs += rhs;
return lhs;
}


Now I would like to join those two containers like follows:


  • If no other element in the target container has the same value A, insert it

  • If another element in the target container has the same value A, add the already present and the new element together



I was wondering if there is an elegant solution (shorter than just having two vectors and looping over them) to this using a different container than vector.

Answer

What about using maps of type std::map<int, Element>, where the key is the A value ?

std::map<int, Element>  m1;
std::map<int, Element>  m2;

// add something in m1 e/o m2

for ( auto const & e : m2 )
 {
   m1[e.first] += e.second;
 }

The key point is that m1[e.first] return a reference to the element in m1 with key e.first, if present, or create it, if not present, returning the reference to the newly created element.

The important point is to have a default contructor for Element that give to the A value of the newly created element a special value with the meaning "absorb the A value from the adding Element".

But can be that you can give away the A value in Element if it's only used as the key for the map.

Comments