求问equal_range
小弟最近在学习STL,刚写了一个程序(代码如下),如何用equal_range()来得到符合一定条件的所有值?(比如下面程序中如何得到所有5到10之间的数?) 请各位大侠帮帮小弟!
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
using namespace std;
template<typename T>
struct BewteenValues:public unary_function<T, bool>
{
BewteenValues( T x, T y):xx(x),yy(y){}
T xx,yy;
inline bool operator() (const T& a) const
{
return a < xx && yy > a;
}
};
void print(const vector<int>& v)
{
for(vector<int>::const_iterator it = v.begin();
it != v.end(); ++it)
cout<<*it<<'\t';
cout<<endl<<endl;
}
int main()
{
vector<int> vect;
for(int i = 0; i != 10; ++i)
{
vect.push_back(i);
vect.push_back(i);
}
print(vect);
cout<<endl;
typedef vector<int>::const_iterator ptr;
cout<<"请输入要查找的值:";
int a;
cin>>a;
pair<ptr, ptr> v_pair1 = equal_range(vect.begin(), vect.end(), a );
// pair<ptr,ptr> v_pair2 = equal_range(vect.begin(), vect.end(), 0, BewteenValues<int>(a,a + 5) ); //编译错误,为什么?
// 这里如何得到5到10之间的所有数?
ptr ptr1 = v_pair1.first,
ptr2 = v_pair1.second;
//ptr3 = v_pair2.first,
//ptr4 = v_pair2.second;
while(ptr1 != ptr2)
{
cout<<*ptr1++<<'\t';
}
cout<<'\n';
/*
while(ptr3 != ptr4)
{
cout<<*ptr1++<<'\t';
}*/
return 0;
}
[解决办法]
仿函数是接受2个参数的
[解决办法]
这种情况下用remove_if比较合适
[解决办法]
sorry
是remove_copy_if
#include <iostream>#include <vector>#include <algorithm>#include <utility>#include <functional>using namespace std;template <typename T>struct BewteenValues:public unary_function <T, bool>{ BewteenValues( T x, T y):xx(x),yy(y){} T xx,yy; inline bool operator() (const T& a) const { if( xx>a && a<yy ) return true; return false; }};void print(const vector <int>& v){ for (vector <int>::const_iterator it = v.begin(); it != v.end(); ++it) cout <<*it <<' '; cout <<endl <<endl;}int main(){ vector <int> vect; for (int i = 0; i != 10; ++i) { vect.push_back(i); vect.push_back(i); } print(vect); cout <<endl; typedef vector <int>::const_iterator ptr; cout <<"请输入要查找的值:"; int a=5; //cin>>a; vector<int> out; out.resize( vect.size() ); out.erase( remove_copy_if( vect.begin(),vect.end() , out.begin() , BewteenValues<int>(a,a+5 ) ) , out.end() ); ptr ptr1 = out.begin(); ptr ptr2 = out.end(); while (ptr1 != ptr2) { cout <<*ptr1++ <<' '; } cout <<'\n'; return 0;}
[解决办法]
比如下面程序中如何得到所有5到10之间的数?
==========
#include <iostream>#include <algorithm> #include "boost/lambda/lambda.hpp"#include "boost/lambda/if.hpp" using namespace boost::lambda;using namespace boost;using namespace std; int main(){ int arr1[] = { 2, 3, 5, 4, 1, 9, 6, 10, 11, 7}; for_each(arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]), if_then(_1 > 5 && _1 < 10, cout << _1 << " " )); cout << endl; cin.get();}
[解决办法]