为什么需要std :: minmax_element?

Che*_* OT 4 c++ stl-algorithm

为什么我们需要的组合版本std::min_element,并std::max_elementstd::minmax_element?它只是用于保存比较或其背后的其他好处吗?

Tar*_*ama 10

std::min_element并且std::max_element需要在返回之前遍历整个容器.如果您使用std::min_element后跟std::max_element那么两次遍历,而如果您使用std::minmax_element那么您只需要一次.

所以,是的,它只是"只是"用于保存比较,但我认为将所需的工作量减半,以便在不损失清晰度的情况下检索所需的数据是非常值得的.

  • 另请注意,`std :: minmax_element`找到_last_最大元素,而`std :: max_element`找到_first_最大元素.[来源](http://en.cppreference.com/w/cpp/algorithm/minmax_element) (5认同)