user1706047
user1706047

Reputation: 359

Maps addition with key as a structure

    typedef struct A{
      string id;
      long date;
      // operator = and < overloading
    }Test;

Map<Test, double> testMap[2];

In code, the testMap array is filled with keys and values with some business logic.

I need to compute the total double value of both the maps for every A.id . Please note the summation should be based on only A.id not by the whole structure key.
To achieve this i can apply the normal brute force approach using for loop and get the result.

But I am trying to find if any alternative solution for this problem that can optimize code. Please suggest.

Upvotes: 0

Views: 75

Answers (1)

Galik
Galik

Reputation: 48615

One way to do this would be to apply nested std::accumulate twice, once to sum up the arrays and for each array to sum up the map contents:

struct Test
{
    string id;
    long date;
    bool operator<(Test const& test) const
    {
        if(date == test.date)
            return id < test.id;
        return date < test.date;
    }
};

double sum_per_id(std::array<std::map<Test, double>, 2> const& testMapArray,
    std::string const& id)
{
    return std::accumulate(std::begin(testMapArray), std::end(testMapArray), 0.0,
    [&id](double d, std::map<Test, double> const& testMap)
    {
        return d + std::accumulate(std::begin(testMap), std::end(testMap), 0.0,
        [&id](double d, std::map<Test, double>::value_type const& p)
        {
            if(id == p.first.id)
                return d + p.second;
            return d;
        });
    });
}

int main()
{
    std::array<std::map<Test, double>, 2> testMapArray;

    testMapArray[0][{"A", 0}] = 0.1;
    testMapArray[0][{"B", 1}] = 0.2;

    testMapArray[1][{"A", 2}] = 0.3;
    testMapArray[1][{"B", 3}] = 0.4;

    std::cout << "sum: " << sum_per_id(testMapArray, "A") << '\n';
}

Output:

sum: 0.4

Upvotes: 1

Related Questions