[英]Is there a function like lower_bound that returns the last value instead of the first?
For example, if I have a sorted array 例如,如果我有一个已排序的数组
{1,1,1,1,1,4,5}
and I want to know the rightmost index of 1
, is there a function that will allow me to do that? 我想知道的最右边的指标
1
,有一个功能,让我这样做呢? (Apart from reverse sorting the array) (除了反向排序数组)
This should work: 这应该工作:
auto p = std::equal_range( std::begin(v), std::end(v), 1 );
if( p.first != p.second ) {
auto it = p.second - 1;
//...
}
There's none so you should craft one on your own. 没有,所以你应该自己制作一个。
template<class Ctr, class Elem> auto rightmost(Ctr &&c, Elem &&e) {
using std::begin;
using std::end;
auto b{begin(c)};
auto retVal{std::upper_bound(b, end(c), e)};
return retVal == b? b : --retVal;
}
#include <iostream>
#include <array>
#include <algorithm>
#include <iterator>
int main()
{
std::array<int, 6> data({2,2,2,2,4,7});
auto it = std::upper_bound(data.begin(), data.end(), 2);
int index = std::distance(data.begin(), it) - 1;
std::cout << "index for last '2' is " << index << std::endl;
}
output: 输出:
index for last '2' is 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.