如何找到向量中最高值的索引,如果有两个"greatest"索引,则默认为较大的索引?
How can I find the index of the highest value in a vector, defaulting to the greater index if there are two "greatest" indices?
我一直在使用std::max_element(vec)
,但据我所知,如果两个"最大"索引相等,它会返回最小的索引。
例:
vector<int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};
std::max_element(v)
会引用v[4]
,但出于我的项目的目的,我需要它引用v[8]
。最好的方法是什么?
你可以使用这个
max_element(v.rbegin(), v.rend());
指最大值的最大索引。
例如
#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;
int main()
{
vector<int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};
*max_element(v.rbegin(), v.rend())=-1;
for (auto i: v) cout << i << ' ';
}
产生输出
1 2 3 4 5 3 3 2 -1
如上所述,上述方法返回反向迭代器,如 @BoBTFish 所示。要获得前向迭代器,您可以这样做:
#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;
int main()
{
vector <int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};
reverse_iterator < vector <int> :: iterator > x (max_element(v.rbegin(), v.rend()));
vector <int> :: iterator it=--x.base(); // x.base() points to the element next to that pointed by x.
*it=-1;
*--it=0; // marked to verify
for (auto i: v) cout << i << ' ';
}
产生输出
1 2 3 4 5 3 3 0 -1
^
可以看出,迭代器it
是一个前向迭代器。
制作自己的函数非常容易:
/* Finds the greatest element in the range [first, last). Uses `<=` for comparison.
*
* Returns iterator to the greatest element in the range [first, last).
* If several elements in the range are equivalent to the greatest element,
* returns the iterator to the last such element. Returns last if the range is empty.
*/
template <class It>
auto max_last(It first, It last) -> It
{
auto max = first;
for(; first != last; ++first) {
if (*max <= *first) {
max = first;
}
}
return max;
}
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- Azure Kinect 使用正文索引映射裁剪正文
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 数组索引重载错误
- 如何找到向量中最高值的索引,如果有两个"greatest"索引,则默认为较大的索引?