我创建了一个地图,其中包含各种事件编号的关键字。然后,每个事件编号都存储一系列数值(粒子质量 - DiLept_M)作为其数据。我想迭代每个事件编号,找到最接近另一个值的每个键的粒子质量。例如
12345: 3098.5 3099.1 8097.3 4356.5
这里的事件编号是12345,以下数字都是粒子质量。我想在新地图中将事件编号和粒子质量(壁橱)存储到3096。
std::map< Int_t, std::vector<Double_t> > MapOfEventsAndMasses;
for(int i=0; i<tree->GetEntries();i++){ //loop through the data
tree->GetEntry(i);
if(MapOfEventsAndMasses.find(event_number) == MapOfEventsAndMasses.end()){
std::vector<Double_t> tempVec;
tempVec.push_back(DiLept_M);
}
else{
MapOfEventsAndMasses[event_number].push_back(DiLept_M);
}
std::map< Int_t, std::vector<Double_t> >::iterator Iter1;
Iter1 = MapOfEventsAndMasses.begin();
std::map< Int_t, std::vector<Double_t> >::iterator Iter1_End;
Iter1_End = MapOfEventsAndMasses.end();
for ( ; Iter1 != Iter1_End; Iter1++){
Int_t event_number = Iter1->first;
std::vector<Double_t> DiLept_M = Iter1->second;
for( int j=0; j < DiLept_M.size(); i++){
// NOT SURE WHAT TO DO HERE
}
} //Closing for loop
从集合中找到最接近给定值的质量背后的基本概念是迭代集合并不断更新最小的质量,将新质量与先前最小的质量进行比较。请参阅代码中的注释以了解如何完成此操作。
#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';
}
}
我没有重复使用你的任何代码,因为目前还不清楚前几个方面做了什么,下半部分用于迭代地图,大大简化了基于范围的循环。这也具有能够独立于演示目的的优点。