给定一对具有2个字段x和y的结构向量(在任一向量中找不到重复的x),如何为每个匹配的X对求和每个值Y(或者简单地使用Y表示不匹配X ) 是否有捷径可寻?我尝试排序,似乎必须有一种方法来有效地做到这一点,而不使用std :: map
示例:
v1 = [{x = 1,y = 2},{x = 1000,y = 3},{x = 3,y = 2}]
v2 = [{x = 0,y = 0},{x = 1,y = 1},{x = 3,y = -3}]
PairWiseSum(v1,v2)= [{x = 0,y = 0},{x = 1,y = 3},{x = 3,y = -2},{x = 1000,y = 3 }]
struct mystruct{
mystruct(int x, double y) {
X= x;
Y= y;
}
int X;
double Y;
bool operator < (const mystruct& other) const
{
return (x < other.x);
}
};
std::vector<mystruct> PairWiseSum(std::vector<mystruct> s1,std::vector<mystruct> s2)
{
std::vector<mystruct> sumVector;
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
...
return sumVector;
}
答案 0 :(得分:1)
浏览s1
和s2
,比较每个集合中的当前项目。如果x
值相同,请将它们一起添加。否则,输出mystruct
值较小的x
。
std::vector<mystruct> PairWiseSum(std::vector<mystruct> s1, std::vector<mystruct> s2)
{
std::vector<mystruct> sumVector;
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
for (auto current1 = begin(s1), current2 = begin(s2); current1 != end(s1) || current2 != end(s2); )
{
if (current1 == end(s1))
sumVector.push_back(*current2++);
else if (current2 == end(s2))
sumVector.push_back(*current1++);
else if (current1->X < current2->X)
sumVector.push_back(*current1++);
else if (current1->X > current2->X)
sumVector.push_back(*current2++);
else
{
sumVector.emplace_back(current1->X, current1->Y + current2->Y);
current1++;
current2++;
}
}
return sumVector;
}