【问题标题】:Finding minimum element of a vector in C++在 C++ 中查找向量的最小元素
【发布时间】:2017-07-20 20:37:45
【问题描述】:

我试图在 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 的值在哪里?

【问题讨论】:

  • minIt - vec.begin()

标签: c++ vector


【解决方案1】:

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

【讨论】:

  • 感谢您的精彩回答!你能扩展它来处理二维向量吗?我将通过编辑更新我的问题!
  • 最好从头问一个新问题。我认为答案会非常不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2020-08-12
  • 1970-01-01
  • 2019-09-25
  • 2014-05-21
  • 2020-05-08
  • 1970-01-01
相关资源
最近更新 更多