2016-04-05 14 views
0

2つのフィールドxとy(どちらのベクトルにも重複するxがない)の構造体のベクトルのペアが与えられた場合、Xの各一致するペアまたは単純に一致するXにYを使用する)これを行う簡単な方法はありますか?私は、ソート試み、かつ効率的にSTD ::マップを使用せずにこれを行う方法がなければならないようだC++/c構造体配列の賢い和

例:

V1 = [{X = 1、Y = 2}、{X = 1000 x = 1、y = 1}、{x = 3、y = 1}、y = 3}、{x = 3、y = 2} (x1、v2)= [{x = 0、y = 0}、{x = 1、y = 3}、{x = 3、y = -2}、{x = 3、y} 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

もっと説明してみると、人々はあなたが望むものを理解する時間を無駄にすると思います。 – Elyasin

答えて

1

ウォークスルーs1s2で、各コレクションの現在のアイテムを比較します。 xの値が同じ場合は、それらを一緒に追加します。それ以外の場合は、x値の小さいmystructを出力します。

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

それを試して、素晴らしい作品!もちろん、いくつかのテストケースを投げていきます。ありがとう! –