使用boost :: bind排序 [英] sort using boost::bind
问题描述
bool pred(int k, int l, int num1, int num2)
{
return (num1 < num2);
}
int main()
{
vector <int> nums;
for (int i=50; i > 0; --i)
{
nums.push_back(i);
}
std::sort (nums.begin(), nums.end(), boost::bind(&pred, 5, 45));
}
我是新手. 我正在学习使用boost :: bind,我想对一个整数向量进行排序,并去除向量中大于45且小于5的所有那些元素.很难做到这一点.如果有人可以帮助我做到这一点会很好吗?
I am a boost newbie. I was learning to use boost::bind and I wanted to sort a vector of integers and get rid of all those elements in the vector that are greater than 45 and less than 5. Had a hard time doing it. Would be great if anyone could help me do it?
我面临问题的原因是因为我在遍历向量进行排序时试图摆脱向量元素.我知道如果我先对其进行排序然后从中删除元素会容易得多.但是我想这样做.感谢您的帮助.
The reason I am facing problem is because I am trying to get rid of a vector element while iterating through the vector to sort it. I know it would be much easier if i sort it first and then remove elements from it. But I want to do it this way. Any help is appreciated.
推荐答案
您不能从sort
执行此操作.
删除sort
之前或之后的元素.
Remove the elements before or after sort
.
bool outOfRange(int low, int high, int num) {
return low > num || num > high;
}
...
nums.erase(
std::remove_if(nums.begin(), nums.end(),
boost::bind(&outOfRange, 5, 45, _1)),
nums.end()
);
尽管您实际上根本不需要boost::bind
.哎呀,我们也可以使它更加通用:
Though you really don't need boost::bind
at all. Heck, we can make it a bit more generic too:
template<typename T, class cmp = std::less<T> >
struct outOfRange : std::unary_function<T, bool> {
outOfRange(const T &low, const T &high) : low(low), high(high) {}
bool operator()(const T &val) { return cmp()(val, low) || cmp()(high, val); }
const T &low, &high;
}
...
nums.erase(
std::erase_if(nums.begin(), nums.end(), outOfRange<int>(5, 45)),
nums.end()
);
这篇关于使用boost :: bind排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!