如何从具有(值> 0)的向量中获取最小值
How to get a minimum value from a vector with (value > 0)
我正在尝试将向量中不为或小于 0 的所有元素减少某个值。
我还没有真正尝试过任何东西,因为我无法解决这个问题,但是我需要,例如,来自 vector{1, 2, 3, 0, -1}
的值 vector[0]
我不想排序或删除任何值,我需要向量保持其 "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
}
我期望例如:来自向量
A = {1, 2, 3, 4, 0, -1}
B = {53, 36, 205, -8, -45, -93}
获得:
A[0]
B[1]
(这些只是随机向量来做一些例子)
您可以像这样使用自定义累积:
#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;});
}
如果向量中没有严格正的元素,它returns整数的最大值。
这是一个相当未知的用例 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));
这对输入向量的 copy 进行排序。对于简单的情况,这是最好的 effort/perf ;)
[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);
这会扫描已排序的 v
以查找第一个非负数(不小于 1)的元素,并 returns 对其进行迭代。当心,如果 v
的元素都不是正数,它 returns 是一个无效的迭代器。我会让你解决这个问题 ;)
我正在尝试将向量中不为或小于 0 的所有元素减少某个值。
我还没有真正尝试过任何东西,因为我无法解决这个问题,但是我需要,例如,来自 vector{1, 2, 3, 0, -1}
的值 vector[0]
我不想排序或删除任何值,我需要向量保持其 "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
}
我期望例如:来自向量
A = {1, 2, 3, 4, 0, -1}
B = {53, 36, 205, -8, -45, -93}
获得:
A[0]
B[1]
(这些只是随机向量来做一些例子)
您可以像这样使用自定义累积:
#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;});
}
如果向量中没有严格正的元素,它returns整数的最大值。
这是一个相当未知的用例 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));
这对输入向量的 copy 进行排序。对于简单的情况,这是最好的 effort/perf ;)
[
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);
这会扫描已排序的 v
以查找第一个非负数(不小于 1)的元素,并 returns 对其进行迭代。当心,如果 v
的元素都不是正数,它 returns 是一个无效的迭代器。我会让你解决这个问题 ;)