How to get a minimum value from a vector with (value > 0)

时间:2019-04-08 13:15:07

标签: c++ vector minimum

I'm trying to reduce by some value all the elements of a vector that are not or less than 0.

I haven't really tried anything because I just can't get around with this, but I Need, for example, from a vector{1, 2, 3, 0, -1} the value vector[0] I don't want to sort or remove any value, I need the vector to keep its "structure".

#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
}

I expect for example: from vectors

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

to get:

A[0]
B[1]

(Those are just random vectors to make some examples)

2 个答案:

答案 0 :(得分:2)

You can use a custom accumulation like this:

#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;});
}

It returns the max for an integer if there are no strictly positive element in the vector.

答案 1 :(得分:2)

This is a use case for the rather unknown std::lower_bound:

int smallest_positive(std::vector<int> v)
{
    std::sort(begin(v), end(v));
    return *std::lower_bound(begin(v), end(v), 0);
}

std::sort(begin(v), end(v));

This sorts a copy of the input vector. For simple cases, this is the best effort/perf you can get ;)


[std::lower_bound] returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.

std::lower_bound(begin(v), end(v), 1);

This scans the sorted v for the first element that is not negative (not less than 1) and returns an iterator to it. Beware, it returns an invalid iterator if no element of v is positive. I'll let you fix that ;)