gpt4 book ai didi

c++ - 如何写一个n元否定器?

转载 作者:行者123 更新时间:2023-11-28 05:19:35 26 4
gpt4 key购买 nike

一元和二元否定符的用处很容易理解。

一元否定符示例(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 作为 not1not2 的替代品,就像 bindbind1stbind2nd 比较?

谢谢

最佳答案

自 C++17 std::not_fn将可用:

auto between = [](int value, int lowerValue, int upperValue) {
return lowerValue < value && value < upperValue;
};

int elems_between = std::count_if(std::cbegin(values), std::cend(values),
std::bind(std::not_fn(between), std::placeholders::_1, lowerValue, upperValue));

wandbox example

关于c++ - 如何写一个n元否定器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41804603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com