我有两个谓词 vector :
typedef std::function<bool(int)> pred;
vector<pred> v1;
vector<pred> v2;
我需要将它们合并为一个,但是第二个 vector 中的谓词应该反转(即它们应该返回 true
,在它们通常返回 false
的情况下)。所以,实际上我需要一种“反转”包装器。
我创建了一个反转函数和一个包含原始谓词并反转其值的结构:
struct inverted
{
pred pr;
inverted(pred pr_) : pr(pr_) {}
bool operator () (int i) {return !pr(i);}
};
pred CreateInverted(pred pr)
{
return inverted(pr);
}
使用这个, vector 谓词的反转可能看起来像:
transform( v2.begin(), v2.end(), v2.begin(), CreateInverted );
但我想知道是否有更好的解决方案,特别是基于标准库?
没有 C++11,允许使用 Boost。
最佳答案
如果您的谓词遵循某些约定,您可以使用 std::not1
来创建反向谓词。这是一个例子:
struct foobar : std::unary_function<bool, int>
{
bool operator()(int value) const { return value > 42; }
};
do_something_if(values.begin(), values.end(), std::not1(foobar());
关于c++ - 如何反转它们的 std::vector<> 中每个谓词的意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961262/