将地图的每个键中的数字数据与另一个数值进行比较

时间:2017-10-13 15:26:18

标签: c++ iterator maps

我创建了一个地图,其中包含各种事件编号的关键字。然后,每个事件编号都存储一系列数值(粒子质量 - DiLept_M)作为其数据。我想迭代每个事件编号,找到最接近另一个值的每个键的粒子质量。例如

12345:3098.5 3099.1 8097.3 4356.5

此处的事件编号为12345,以下数字均为粒子质量。我想在新地图中将事件编号和粒子质量(壁橱)存储到3096。

{{1}}

1 个答案:

答案 0 :(得分:0)

从集合中找到最接近给定值的质量背后的基本概念是迭代集合并不断更新最小的质量,将新质量与先前最小的质量进行比较。请参阅代码中的注释,了解如何完成此操作。

#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <vector>

int main() {
    std::map<int, std::vector<double>> map { // Data to look through.
            {1, {3098.0, 3097.5, 3099.0, 3094.0}},
            {2, {3098.0, 3093.0, 3095.0, 3094.0}}
    };
    std::map<int, double> results; // Map of events and and their closest masses.
    const double mass = 3096; // Mass to search for.

    for (auto& kv : map) { // Iterates the data.
        const int event_number = kv.first;
        const std::vector<double>& masses = kv.second;

        for (double m : masses) { // Iterates the vector of masses.
            // Attempts to find the element for the event in the results map.
            auto value = results.find(event_number);

            // If unsuccessful, find() returns end() iterator. If unsuccessful,
            // creates a new element with the current mass without comparison
            // (because there is nothing to compare against).
            if (value == results.end()) {
                results.emplace(event_number, m);
            } else if (fabs(mass - m) < fabs(mass - value->second)) {
                // Sets the mass to the current mass if the difference between
                // the current mass and the one to search for is smaller than
                // that of the previously smallest seen mass.
                value->second = m;
            }
        }
    }

    for (auto r : results) { // Prints the results.
        std::cout << r.first << ", " << r.second << '\n';
    }
}

我没有重复使用你的任何代码,因为目前还不清楚前几个方面做了什么,下半部分用于迭代地图,大大简化了基于范围的循环。这样做的另一个好处是能够独立地进行演示。