- 论坛徽章:
- 14
|
回复 11# BuTa丶潇
用equal_range的话,我写个demo
如果你的编译器支持最新的C++标准,那么- #include <vector>
- #include <algorithm>
- #include <iostream>
- using namespace std;
- void foo( const double* buf, size_t n, double a, double b )
- {
- std::pair<const double*,const double*> range = std::equal_range( buf+0, buf+n, a
- , [a,b](double e1, double e2) {
- int v1 = e1<a ? -1 : ( e1<=b ? 0 : 1 );
- int v2 = e2<a ? -1 : ( e2<=b ? 0 : 1 );
- return v1 < v2;
- } );
- if( range.first == range.second )
- {
- std::cout << "不存在" << std::endl;
- return;
- }
- std::cout << (range.first-buf) << " - " << (range.second-buf-1) << std::endl;
- }
- template<size_t N>
- inline void foo( const double (&buf)[N], double a, double b )
- {
- foo( buf, N, a, b );
- }
- int main()
- {
- double buf[] = { 3 , 3.5 , 5.7 , 6.8 , 11 , 15.4 };
- foo( buf, 0.3, 10 ); // 0-3
- foo( buf, 1, 2 ); //
- foo( buf, 19.4, 22 ); //
- foo( buf, 3.5, 17 ); // 1-5
- return 0;
- }
复制代码 如果你的编译器比较老旧,用- #include <vector>
- #include <algorithm>
- #include <iostream>
- using namespace std;
- struct ablesser_
- {
- ablesser_( double a, double b ) : a_(a), b_(b)
- {
- }
- bool operator()( double e1, double e2 ) const
- {
- int v1 = e1<a_ ? -1 : ( e1<=b_ ? 0 : 1 );
- int v2 = e2<a_ ? -1 : ( e2<=b_ ? 0 : 1 );
- return v1 < v2;
- }
- double a_, b_;
- };
- void foo( const double* buf, size_t n, double a, double b )
- {
- std::pair<const double*,const double*> range = std::equal_range( buf+0, buf+n, a, ablesser_(a,b) );
- if( range.first == range.second )
- {
- std::cout << "不存在" << std::endl;
- return;
- }
- std::cout << (range.first-buf) << " - " << (range.second-buf-1) << std::endl;
- }
- template<size_t N>
- inline void foo( const double (&buf)[N], double a, double b )
- {
- foo( buf, N, a, b );
- }
- int main()
- {
- double buf[] = { 3 , 3.5 , 5.7 , 6.8 , 11 , 15.4 };
- foo( buf, 0.3, 10 ); // 0-3
- foo( buf, 1, 2 ); //
- foo( buf, 19.4, 22 ); //
- foo( buf, 3.5, 17 ); // 1-5
- return 0;
- }
复制代码 当然,代码都有些晦涩,最佳的办法应该是调用 std::lower_bound 获得第一个下标,std::upper_bound 获得第二个下标(其实你要的是这个值之前一位置) |
|