我有一个值数组和一种用于查找数组中最大元素索引的技术。
value = distance(arrayOfValues, max_element(arrayOfValues, arrayOfValues + N));
但是,如果有最大值的多个实例,例如{3,1,3,4,4,3,2}它只返回最小的索引(在本例中为3),而我希望它返回最大的索引,在这种情况下为4.
我能想到的唯一方法是创建一个与“arrayOfValues”相同的新数组。但反之,然后应用上述方法。
是否有更简单的方法可以避免创建新数组?也许通过操纵上面的代码?
答案 0 :(得分:3)
您可以提供自定义比较器来比较地址:
const int index =
std::distance(std::begin(arrayOfValues),
std::max_element(std::begin(arrayOfValues), std::end(arrayOfValues),
[](const int& lhs, const int& rhs) {
return std::make_tuple(lhs, &lhs)
< std::make_tuple(rhs, &rhs);
}
));
答案 1 :(得分:3)
在您的范围内使用反向迭代器。
您将end
传递给反向迭代器构造函数以获得反向开始,然后开始反向结束。
template<class It>
std::reverse_iterator<It> rit(It i){return {i};}
template<class C>
struct backwards_t {
C c;
auto end() {
using std::begin;
return rit(begin(c));
}
auto begin() {
using std::end;
return rit(end(c));
}
};
template<class C>
backwards_t<C> backwards(C&&c){return {std::forward<C>(c)};}
是一种C ++方法。
auto yarra = backwards(array);
auto it = std::max_element(yarra.begin(), yarra.end());
这也允许您在backwards
循环中调用for(:)
并向后迭代。
答案 2 :(得分:2)
在for循环中添加if语句。有点像...
int indexToReturn = 0;
int indexValue = 0;
int newValue = 0;
for (int i = 0; i < arrayCount; i++) {
newValue = arrayOfValues[i];
if (newValue >= indexValue) {
indexToReturn = i;
indexValue = newValue;
}
// At the end of this loop the value you want is indexToReturn
}
答案 3 :(得分:2)
你可能有这样的事情:
int maxIdx = 0;
for(int i = 0; i < n; ++i)
if(a[maxIdx] > a[i])
maxIdx = i;
return maxIdx;
您只需要在if语句中添加一个字符:
if(a[maxIdx] >= a[i])
maxIdx = i;