Reputation: 43
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? (Apart from reverse sorting the array)
Upvotes: 3
Views: 174
Reputation: 7198
#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
Upvotes: 1
Reputation: 44258
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;
//...
}
Upvotes: 4
Reputation: 11940
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;
}
Upvotes: 1