2016-04-05 30 views
0

2 x ve y alanlı vektörlerin bir çifti verildiğinde (her iki vektörde de x kopyası bulunmaz), her bir eşleşen X çifti için her bir Y değerini nasıl toplarım? ya da sadece eşleşen X için kullanmayınız. X) Bunu yapmanın kolay bir yolu var mı? I sıralama güvenilir ve etkili şekilde std :: ilk kullanmadan bunu yapmanın bir yolu olmalı gibi görünüyorC++/c struct array çifti bilge toplam

örnek:

v1 = [{x = 1 olduğunda, y = 2}, {x = 1000 , y = 3}, {x = 3, y = 2}]

v2 = [{x = 0, y = 0}, {x = 1, y = 1}, {x = 3, y = -3}]

PairWiseSum (sürüm 1, v2) 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

Daha iyi açıklamaya çalışın, insanların ne istediğini anlamak için zamanlarını boşa harcadığını düşünüyorum. – Elyasin

cevap

1

Her koleksiyondaki geçerli öğeyi karşılaştırarakve s2. x değeri aynıysa, bunları birlikte ekleyin. Aksi halde, mystruct değerini daha küçük x değeriyle çıkarın.

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

Bunu denedim, harika çalışıyor! Tabii ki birkaç test vakası atarım. Teşekkürler! –