【问题标题】:Find the minimum number +ve number in c++?在c ++中找到最小数+ve数?
【发布时间】:2013-10-13 02:50:54
【问题描述】:

我想在 C++ 中使用 STL 找到最小数字,我知道语法应该是 min(x,y)。但我想在列表中找到最小的 +ve 数字。不包括-ves。我该怎么做?

P.S 我的数字在一个数组中

【问题讨论】:

  • 如果所有元素都是负数,答案是什么?
  • 在我的问题中不可能发生这种情况:) 但在这种情况下我没有任何线索。

标签: c++ stl min


【解决方案1】:

我会使用std::accumulate 进行适当的操作:

auto minpos = std::accumulate(myrange.begin(), myrange.end(), MAX_VALUE,
                              [](T acc, T x)
                              { return (x > 0 && x < acc) ? x : acc; });

这里T 是您的元素的类型,MAX_VALUE 是该类型的最大值(例如定义为std::numeric_limits&lt;T&gt;::max())。

【讨论】:

    【解决方案2】:

    首先使用remove_if算法将所有负数移动到集合的末尾,然后在正数范围内调用min_element。在 C++11 中

    auto pos = remove_if(coll.begin(), coll.end(), [](int x){ return x < 0; });
    auto min = *min_element(coll.begin(), pos);
    

    如果您不使用 C++11,只需将 lambda 替换为来自 like less

    的预装仿函数

    【讨论】:

      【解决方案3】:

      为了找到最小数字,使用std::min_element 是有意义的。幸运的是,它带有一个可选的比较参数,我们可以使用它:(sample here)

      auto pos = std::min_element(std::begin(arr), std::end(arr),
          [](const T &t1, const T &t2) {return t1 > 0 && (t2 <= 0 || t1 < t2);}
      );
      

      您只需要小心考虑到,如果将正数 t1 与负数进行比较,则它应该始终为真。如果没有一个元素是正数,这将给出数组中第一个数字的位置。如果应将 0 视为肯定的一部分,请将 t1 &gt; 0 更改为 t1 &gt;= 0 并将 t2 &lt;= 0 更改为 t2 &lt; 0

      【讨论】:

      • 或者只是[](T t1, T t2){ return as_unsigned(t1) &lt; as_unsigned(t2); }(参见GotW #93 实现
      【解决方案4】:

      您可以将std::min_elementBoost::filter_iterator 一起使用

      类似:

      struct is_positive_number {
        bool operator()(int x) const { return 0 < x; }
      };
      
      void foo(const std::vector<int>& numbers)
      {
          typedef boost::filter_iterator<is_positive_number, base_iterator> FilterIter;
      
          is_positive_number predicate;
          FilterIter filter_iter_begin(predicate, begin(numbers), end(numbers + N));
          FilterIter filter_iter_end(predicate, end(numbers + N), end(numbers + N));
      
          FilterIter it = std::min_element(filter_iter_begin, filter_iter_end);
      
          if (it != filter_iter_end) {
              // *it is the min elem
          } else {
              // no positive numbers.
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-04
        • 2015-11-29
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-10
        相关资源
        最近更新 更多