连接两个对象容器,如果已经存在则添加元素

Joining two containers of objects, adding elements if already present

本文关键字:如果 存在 元素 添加 两个 对象 连接      更新时间:2023-10-16

我有两个容器的对象类型为:

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;
}

现在我想像这样连接这两个容器:

  • 如果目标容器中没有其他元素具有相同的值A,则插入
  • 如果目标容器中的另一个元素具有相同的值A,则将已经存在的元素和新元素一起添加

我想知道是否有一个优雅的解决方案(比仅仅有两个向量和循环它们短)使用不同的容器而不是向量。

使用类型为std::map<int, Element>的映射,其中键是A的值如何?

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;
 }

关键是m1[e.first]返回对m1中键为e.first的元素的引用,如果存在,或者创建它,如果不存在,返回对新创建元素的引用。

重要的是要有一个Element的默认构造函数,为新创建的元素的A值赋予一个特殊的值,意思是"从添加的Element中吸收A值"。

但是可以在Element中给出A的值,如果它只用作映射的键