【问题标题】:Finding the minimum and maximum values in a std::vector of std::pair在 std::pair 的 std::vector 中查找最小值和最大值
【发布时间】:2019-02-05 07:31:36
【问题描述】:

我正在尝试找出pair<int, std::string> 向量中的最小值和最大值。

我的代码:

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::pair<int, std::string>> pairs;
    pairs = {{6,"a"}, {4,"b"}, {5,"c"}, {8,"d"}, {7,"e"}};

    int min = 0, max = 0;

    // How can I find out the minimum and maximum?

    std::cout << "Minimum Number: " << min << '\n';
    std::cout << "Maximum Number: " << max << '\n';
}

我想要的结果:

Minimum Value: 4
Maximum Value: 8
Program ended with exit code: 0

我怎样才能得到我想要的结果?


到目前为止,这是我的解决方案。

std::sort(pairs.begin(), pairs.end());
min = pairs[0].first;
max = pairs[pairs.size()-1].first;

虽然可行,但我想学习一个比这更简单、更快的解决方案。

【问题讨论】:

标签: c++ vector max min std-pair


【解决方案1】:

你可以使用std::minmax_element:

 const auto p = std::minmax_element(pairs.begin(), pairs.end());
 auto min = p.first->first;
 auto max = p.second->first;

【讨论】:

  • 非常感谢。这比我自己的解决方案更快吗?
  • 复杂度是O(n),而你的是O(n log n)。 (它使用的比较比std::min_element 后跟std::max_element 还要少)。
  • 或使用 C++17:auto&amp;&amp; [min, max] = std::minmax_element(begin(pairs), end(pairs)); 为简洁起见。
  • @Deduplicator:还有std::pair&lt;int, std::string&gt;::first可以调用。
猜你喜欢
  • 2013-03-08
  • 2018-05-17
  • 2016-09-02
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多