jra*_*amm 6 c++ vector max min
我有一个vectors double。我希望找到两者:
x。x。例如,如果我有一个向量:
std::vector<double> vec = {0, 1.0, 3.0, 4.0, 5.0};
Run Code Online (Sandbox Code Playgroud)
和一个值
x = 2.6;
Run Code Online (Sandbox Code Playgroud)
我希望找到1.0和3.0。
做到这一点最有效的方法是什么?
我有类似的东西:
double x1, x2; // But these need to be initialised!!!
double x = 2.6;
for (i = 0; i < vec.size(); ++i)
{
if (vec[i] >= x && vec[i] < x2)
x2 = vec[i];
if (vec[i] <= x && vec[i] > x1)
x1 = vec[i];
}
Run Code Online (Sandbox Code Playgroud)
但是我怎样才能初始化x1和x2呢?我可以使 x2 成为向量的最大值,使 x1 成为最小值,但这需要对数据进行初始传递。有什么办法可以更有效地做到这一点吗?
编辑:
我认为我可以/不能对数据做出一些假设:
0)您可以使用std::lower_bound:
#include <iterator>
#include <algorithm>
template<class ForwardIt, class T>
std::pair<ForwardIt, ForwardIt> hilo(ForwardIt first, ForwardIt last, T const &value)
{
if (first != last)
{
auto lb = std::lower_bound(first, last, value);
auto prelbd = std::distance(first, lb) - 1;
if (lb == last) return{ std::next(first, prelbd), last };
if (!(value < *lb)) return{ lb, lb };
if (lb == first) return{ last, first };
return{ std::next(first, prelbd), lb };
}
return{ last, last };
}
Run Code Online (Sandbox Code Playgroud)
可以这样使用:
std::vector<double> vec = { -1.0, -1.0, 0.0, 1.0, 3.0, 3.0, 3.0, 3.0, 4.0, 5.0, 5.0 };
// if not ordered
//std::sort(vec.begin(), vec.end());
double x = 5.0;
auto b = hilo(vec.begin(), vec.end(), x);
if (b.first != vec.end())
{
std::cout << "First index: " << std::distance(vec.begin(), b.first)
<< "(value " << *b.first << ")\n";
}
if (b.second != vec.end())
{
std::cout << "Second index: " << std::distance(vec.begin(), b.second)
<< "(value " << *b.second << ")\n";
}
Run Code Online (Sandbox Code Playgroud)
要初始化向量的x1最小值x2和最大值,我想你别无选择,只能通过它,除非你std::sort首先调用向量,并按升序或降序排序,然后选择列表的头/尾,根据您的订单,初始化这两个值。
您还可以用于std::min_element从容器中获取最小值,或std::max_element查找容器中的最大元素。