C++ 有没有像lower_bound这样的函数返回最后一个值而不是第一个值?
例如,如果我有一个排序数组C++ 有没有像lower_bound这样的函数返回最后一个值而不是第一个值?,c++,arrays,function,sorting,C++,Arrays,Function,Sorting,例如,如果我有一个排序数组 {1,1,1,1,1,4,5} 我想知道1的最右边的索引,是否有一个函数允许我这样做?(除了对数组进行反向排序)这应该可以: auto p = std::equal_range( std::begin(v), std::end(v), 1 ); if( p.first != p.second ) { auto it = p.second - 1; //... } 没有,所以你应该自己制作一个 template<class Ctr, class
{1,1,1,1,1,4,5}
我想知道1
的最右边的索引,是否有一个函数允许我这样做?(除了对数组进行反向排序)这应该可以:
auto p = std::equal_range( std::begin(v), std::end(v), 1 );
if( p.first != p.second ) {
auto it = p.second - 1;
//...
}
没有,所以你应该自己制作一个
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;
}
模板自动最右边(Ctr&c、Elem&e){
使用std::begin;
使用std::end;
自动b{begin(c)};
自动返回{std::上界(b,end(c),e)};
return retVal==b?b:--retVal;
}
#包括
#包括
#包括
#包括
int main()
{
数组数据({2,2,2,4,7});
auto it=std::上限(data.begin(),data.end(),2);
int index=std::distance(data.begin(),it)-1;
Std::Cude:Std::UpthyLoad——1 我确实考虑过上限,但它不能完成我想做的事。@贾斯廷不会给他5的索引吗?使用UpjiField并有条件地将索引减少1。
#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;
}