如何在向量的给定索引范围内查找最小元素
How to find minimum element in a given range of indices for a vector?
如何在给定的索引范围内找到std::vector
的最小元素?
假设向量是
vector<int> v = {1,2,3,4,5};
所以
min_element(v.begin(), v.end());
会给1
.
但是,如果我们想要从指数1
到3
的最小值怎么办?
也就是说,在元素{2,3,4}
v
中,这是2
。
由于std::min_element
在[first, last)
范围内运行(从first
到过去end
),我们需要提供如下:
const auto begin = v.begin() + 1;
const auto end = begin + 3;
int min = *std::min_element(begin, end);
或使用std::next
使其通用(信用 @Slava)
auto min = *std::min_element(std::next(v.begin(), 1), std::next(v.begin(), 4));
要将其包装在帮助程序函数中,请执行以下操作:
template<typename Container, typename Predicate = std::less<>>
auto min_element(
const Container &container,
std::size_t startIdx,
std::size_t endIdx,
const Predicate pred = {}) -> std::decay_t<decltype(*(container.begin()))>
// typename Container::value_type // or simply
{
return *std::min_element(std::next(container.begin(), startIdx),
std::next(container.begin(), ++endIdx), pred);
}
现在在主要
std::vector<int> v = { 1, 3, 5, 2, 1 };
const auto startIndex = 1u, endIndex = 3u;
const int min = ::min_element(v, startIndex, endIndex /*, predicate if any*/);
查看实时示例
但是,请确保给定的迭代器有效,否则行为为 UB。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 在C++中查找范围的长度
- 并行用于C++17中数组索引范围内的循环
- 查找给定范围内最长连续 1 的频率
- 检查IP是否在其他IP网络范围内,并查找下一个可用IP
- 对于多个查询,查找在 l 到 r 范围内具有相同元素的最长公共子数组
- 从给定范围内的向量中查找最大元素
- 如何在向量的给定索引范围内查找最小元素
- 查找范围内元素数量的最快方法
- 在某个范围内查找素数时出现 Sigsegv 错误
- 给定数百万个点,查找位于直线上或距离直线0.2 mm范围内的点
- 使用cctype库搜索函数,以查找某个范围内的数字字符数
- 使用检查功能查找给定范围内的所有回文数
- 在 C+/C++ 的十六进制范围内查找十六进制数
- 在一个范围内查找素数的直观方法
- 'make_error_code' 未在此范围内声明,并且在实例化点通过依赖于参数的查找未找到任何声明
- 在给定范围内查找毕达哥拉斯三元组的个数
- 查找矢量中位于指定范围内的元素
- 算法:查找给定范围内的数字计数