【发布时间】:2016-09-02 20:24:02
【问题描述】:
我有一个 std::vector 的 std::map 值:
std::vector<std::map<std::string, double>> dataPoints;
我想找到最低的low 值,74.0。到目前为止,这是我的应用程序:
#include <vector>
#include <map>
#include <iostream>
int main() {
std::vector<std::map<std::string, double>> dataPoints;
dataPoints.push_back({{{"high", 77.0}, {"low", 74.0}}});
dataPoints.push_back({{{"high", 78.0}, {"low", 75.0}}});
dataPoints.push_back({{{"high", 79.0}, {"low", 76.0}}});
dataPoints.push_back({{{"high", 80.0}, {"low", 77.0}}});
dataPoints.push_back({{{"high", 81.0}, {"low", 78.0}}});
return 0;
}
到目前为止我发现的最接近的是:
double min = std::min_element(dataPoints.begin(), dataPoints.end(), [](std::map<std::string, double> &a, std::map<std::string, double> &b) { return (a["low"] < b["low"]); })["low"];
但这并不完全奏效。
在 JavaScript 中,我可以如下实现:
low = _.min(_.map(dataSegment, function(dataPoints) {
return dataPoint.low;
}));
【问题讨论】:
-
您是否总是有两个条目的
map?因为如果是这样,您可以通过使用std::vector<std::array<std::pair<std::string, double>,2>>获得更好的性能 -
我建议使用 std::pair 而不是 map 来存储 2 个值。像 std::set <:pair double>>.
-
@StoryTeller 不错!谢谢你。性能提升有多明显?另外,向量定义中的“2”参数是什么?
-
你必须进行基准测试才能看到它到底有多好。但是由于内存的局部性,使用连续的数据结构(向量、数组和对)可以减少缓存未命中。至于 2,它是 std::array 固定大小。
-
关于您迄今为止得到的答案的评论建议使用
std::pair:std::pair几乎总是适合这项工作的错误工具。您应该改为使用命名字段定义struct。struct Pair { double high; double low; }; std::vector<Pair> dataPoints;。定义数据类型的代码比使用std::make_pair稍微多一些,但使代码更具可读性。
标签: c++ c++11 dictionary vector stl