我能想到的至少在四個方面與std::min_element
1做到這一點),添加一個 「小於」 的成員函數的struct /類:
struct abc
{
int cost;
int any;
bool operator<(const abc &other) const { // member function
return cost < other.cost;
}
};
int main() {
// ...
// The algorithm will find and use the class operator< by default
abc *ptr = std::min_element(var1, var1 + 5);
}
2)定義自由功能:
bool abc_less(const abc &lhs, const abc &rhs) // free function
{
return lhs.cost < rhs.cost;
}
int main() {
// ...
// Pass a function pointer to the algorithm
abc *ptr = std::min_element(var1, var1 + 5, abc_less);
}
3)定義一個函數對象類型:
struct abc_less // function object
{
bool operator()(const abc &lhs, const abc &rhs) const {
return lhs.cost < rhs.cost;
}
};
int main() {
// ...
// Construct and pass a function object to the algorithm
abc *ptr = std::min_element(var1, var1 + 5, abc_less());
}
4)創建lambda函數:
int main() {
// ...
// Create a lambda at the point of call in this example
abc *ptr = std::min_element(var1, var1 + 5, [](const abc &lhs, const abc &rhs) { return lhs.cost < rhs.cost; });
}
最後,使用返回的迭代器(指針在這種情況下)打印值或偏移:
std::cout << "Value = " << ptr->cost << '\n';
std::cout << "Position = " << (ptr - var1) << '\n'; // or std::distance(var1, ptr)
感謝您給予的答案這種記錄良好的方式。這給了我一種感覺,我對C++ –
稍微複雜一點都不瞭解:如果我需要查找**所有**索引與最小值匹配,該怎麼辦? –
@ Mr.EU:最簡單的方法可能就是使用for循環收集匹配最小值的索引。如果你在一次傳遞中做了這個,那麼可能像[ideone.com上的這段代碼](http://ideone.com/kE21eo) – Blastfurnace