一元和二元否定符的用处很容易理解。
一元否定符( not1 )的示例:
class Even
{
public:
bool operator() (const int& x) const { return x % 2 == 0; }
typedef int argument_type;
};
int values[] = { 9, 1, 8, 2, 7, 3, 6, 4, 5 };
int even = count_if(values, values + 9, Even());
int odd = count_if(values, values + 9, not1(Even())); // <= unary negator
cout << "We have " << even << " even elements in the array.\n";
cout << "We have " << odd << " odd elements in the array.\n";
输出:
We have 4 even elements in the array.
We have 5 odd elements in the array.
二进制否定器( not2 )的示例:
int values[] = { 9, 1, 8, 2, 7, 3, 6, 4, 5 };
// original array
for (int i : values)
cout << i << " ";
cout << "\n";
// array in ascending order
sort(values, values + 9, less<int>());
for (int i : values)
cout << i << " ";
cout << "\n";
// array in descending order
sort(values, values + 9, not2(less<int>())); // <= binary negator
for (int i : values)
cout << i << " ";
cout << "\n\n";
输出:
9 1 8 2 7 3 6 4 5
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
那么 n 元否定符(not3, not4, not5 ... notn)呢?
假设我需要计算集合(可能是数组)中不在两个数字(下限和上限)之间的元素数量。
.
int elems_betweem = count_if(values, values + n, not3(bind(Between<int>(), _1, lowerValue, upperValue)));
.
如何编写not3否定符?
更重要的是,我们是否有一个泛型not
作为 and 的替代者not1
,not2
其方式与bind
vs bind1st
and相同bind2nd
?
谢谢