Scott Morken
Scott Morken

Reputation: 1651

c++/c struct array pair wise sum

Given a pair of vectors of structs with 2 fields x and y (where no duplicate x is found in either vector), how do I sum each value Y for each matching pair of X (or simply use Y for no matching X) Is there an easy way to do this? I tried sorting, and it seems like there must be a way to do this efficiently without using std::map

example:

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

Upvotes: 0

Views: 87

Answers (1)

Bradley Grainger
Bradley Grainger

Reputation: 28172

Walk through s1 and s2, comparing the current item in each collection. If the x value is the same, add them together. Otherwise, output the mystruct with the smaller x value.

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

Upvotes: 1

Related Questions