c++ - 以键作为结构的映射加法

标签 c++ dictionary stl

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

Map<Test, double> testMap[2];

在代码中,testMap 数组填充了键和值以及一些业务逻辑。

我需要为每个 A.id 计算两个映射的总 double 值。请注意,求和应仅基于 A.id 而不是整个结构键。
为实现这一点,我可以使用 for 循环应用正常的强力方法并获得结果。

但我正在尝试寻找可以优化代码的此问题的替代解决方案。请提出建议。

最佳答案

一种方法是应用嵌套的 std::accumulate两次,一次对数组求和,对每个数组求和 map 内容:

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

输出:

sum: 0.4

关于c++ - 以键作为结构的映射加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582066/

相关文章:

C++ 项目无法连接到套接字,出现错误 10093

c++ - 单击 QPushButton 时,将数据从 QLineEdit 转换为 QString。

c++ - 经过这么多循环后,cuda 计算给出了 nan

python - 从可迭代对象创建字典

c++ - 在 std::bitset 中作为运算符重载提供的按位运算(&、^. | 等)是否使用 AVX 或 SSE4 指令?

c++ - 图形模板类

c++ - 如何防止构造类的对象?

arrays - 使用 slice []reflect.Type 作为映射键

python - 为什么python字典的元素没有按顺序打印

c++ - "Proper"用 C++/STL 存储二进制数据的方式