std::min_elementで取り出せる。
これが基本的な使い方。
#include <algorithm>
#include <cassert>
#include <vector>
#include <iostream>
int main(){
std::vector<int> v1 = {3, 1, 4};
const auto& v1_min_element = std::min_element(v1.begin(), v1.end());
if (v1_min_element == v1.end()) {
// 最小値が見つからなかったら
return -1;
}
assert(*v1_min_element == 1); // 最小値である1でなければアサート
}
自分で比較対象を指定することもできる。
#include <algorithm>
#include <cassert>
#include <vector>
#include <iostream>
class Hoge final
{
public:
int a;
int b; // 比較対象
Hoge(int a, int b){
this->a = a;
this->b = b;
}
};
int main(){
std::vector<Hoge> v1 = {Hoge(0, 3), Hoge(1, 1), Hoge(2, 4)};
const auto& v1_min_element = std::min_element(v1.begin(), v1.end(), [](const auto& l, const auto& r){
return l.b < r.b; // 最小値とみなす条件をtrueで返す
});
if (v1_min_element == v1.end()) {
// bの最小値が見つからなかったら
return -1;
}
assert(v1_min_element->b == 1); // bの最小値である1でなければアサート
}
コメントを残す