在C ++中查找向量的最小元素

时间:2017-03-01 13:28:27

标签: c++ vector

我试图在C ++中找到向量的最小元素。我希望返回最低元素的值和向量中索引的位置。这是我尝试过的,

    auto minIt = std::min_element(vec.begin(), vec.end());
    auto minElement = *minIt;
       std::cout << "\nMinIT " << &minIt << " while minElement is " << minElement << "\n"; 

返回以下内容,

MinIT 8152610 while minElement is 8152610

如何获得vec(i)的索引i,其中该值为?

1 个答案:

答案 0 :(得分:12)

std::min_element的返回是迭代器,您使用auto会混淆。

您可以使用

在矢量中获取它的位置

std::distance(vec.begin(), std::min_element(vec.begin(), vec.end()));

更多的是“C ++标准库” - 而不是通用的

std::min_element(vec.begin(), vec.end()) - vec.begin();

虽然对任何一种方式的优点都存在意见分歧。见What is the most effective way to get the index of an iterator of an std::vector?

进一步参考:http://en.cppreference.com/w/cpp/algorithm/min_elementhttp://en.cppreference.com/w/cpp/iterator/distance

相关问题