【发布时间】:2016-08-16 12:37: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,则将已经存在的元素和新元素相加
我想知道是否有一个优雅的解决方案(比只有两个向量并循环它们更短)使用与向量不同的容器来解决这个问题。
【问题讨论】:
-
您的容器是否经常被修改?您是否经常需要按顺序迭代它们?是否应该切换容器取决于这些问题。
-
你错过了
return *this;operator +=