所以我有一个结构向量,它以下面的方式定义和使用:
枚举ID { α, 测试版, 伽马};
使用TimePoint = std :: chrono :: time_point< std :: chrono :: system_clock&gt ;; …
我只是将具有不同ID的对象存储在不同的向量中,每个ID都有一个向量:
std::map<ID, std::vector<pInfo>> pMembers;
如果您不能或不会这样做,那么我将使用过滤迭代器适配器。以下示例使用Boost.Iterator:
auto const filter = [p_id](auto const& id) { return id == p_id; }; auto const compare = [](auto const& a, auto const& b) { return a.tPoint < b.tPoint; }; auto const it = std::min_element(boost::make_filter_iterator(filter, begin(pMembers), end(pMembers)), boost::make_filter_iterator(filter, end(pMembers), end(pMembers)), compare).base();
扩展Remy的答案,这是我写第一种方式的方式:
auto const it = std::min_element(begin(pMembers), end(pMembers), [=](auto const& a, auto const& b) { return std::forward_as_tuple(a.id != p_id, a.tPoint) < std::forward_as_tuple(b.id != p_id, b.tPoint); });
您还可以简单地将基于范围的for应用于此问题,如下所示:
的 DEMO 强>
const pInfo& getNext(const std::vector<pInfo>& pMembers, ID p_id) { const pInfo* p{nullptr}; TimePoint min{TimePoint::max()}; for(const auto& p_i : pMembers) { if(p_i.id == p_id && p_i.tPoint < min) { min = p_i.tPoint; p = &p_i; } } if(!p){ throw std::runtime_error("no data."); } return *p; }