lundi 3 septembre 2018

How to perform GroupBy Sum query on a list?

Background

I have worked with C#.Net + LINQ wherever possible and trying my hand at C++ development for a project I am involved. Of course, I fully realize that C# and C++ are two different worlds.

Question

I have an std::list<T> where T is a struct as follows:

struct SomeStruct{
    int id;
    int rate;
    int value;
};

I need to get a result of group by rate and sum of value. How can I perform GroupBy Sum aggregate function on this list?

Example:

SomeStruct s1;
SomeStruct s2;
SomeStruct s3;

s1.id=1;
s1.rate=5;
s1.value=100;

s2.id=2;
s2.rate=10;
s2.value=50;

s3.id=3;
s3.rate=10;
s3.value=200;

std::list<SomeStruct> myList;
myList.push_front(s1);
myList.push_front(s2);
myList.push_front(s3);

With these inputs I would like to get following output:

rate|value
----|-----
   5|  100
  10|  250

I found a few promising libs such as CINQ and cppitertools. But I couldn't fully understand as I lack sufficient knowledge. It would be great if someone guide me to right direction, I am more than willing to learn new things.

Aucun commentaire:

Enregistrer un commentaire