如何从(值> 0)的向量中获取最小值

PlayLikeMe10YT

我试图将不等于或小于0的向量的所有元素减少一些值。

我还没有真正尝试过任何东西,因为我不能用此得到解决,但我需要的,例如,从vector{1, 2, 3, 0, -1}价值vector[0]我不想排序或删除任何价值,我需要的载体,以保持其“结构”。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> R;
    //I'm sorry I can't provide any code, I can't get around with this
}

我期望例如:从向量

A = {1, 2, 3, 4, 0, -1}
B = {53, 36, 205, -8, -45, -93}

要得到:

A[0]
B[1]

(这些只是随机向量,以举例说明)

马修·布鲁彻(Matthieu Brucher)

您可以使用以下自定义累积:

#include <algorithm>
#include <iostream>
#include <vector>
#include <limits> //std::numeric_limits
#include <numeric> //std::accumulate
#include <iterator> //std::begin, std::end

int main()
{
    std::vector<int> R{1, 2, 3, 4, 0, -1};

    std::cout << std::accumulate(std::begin(R), std::end(R), std::numeric_limits<int>::max(), 
      [](int a, int b){if (b > 0) return std::min(a, b); return a;});
}

如果向量中没有严格的正元素,则它将返回整数的最大值。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章