检查输入 std::array 指针数据是否等于某个常量数组



我有一个函数跟踪,可以简化为:

void foo(const std::array<unsigned long long int, 3>& in)

我想检查 in 的值是否是特定的东西(例如。{1,1,1}(,所以我可以警告/错误。

我已经看到您应该能够在std:array中使用==!=运算符,但是以下失败:

if(in.data() == std::array<unsigned long long int, 3>{1,1,1})

因为:

错误:‘operator==’不匹配(操作数类型为"std::array<long long unsigned int,::const_pointer{akaconst long long unsigned int*}" 和"std::array<long long unsigned int,"(

我知道.data()似乎正在返回一个cosnt_pointer,但我不知道如何解决这个问题来做我想做的事情。我该如何进行这种比较(除了一个朴素的 for 循环,它似乎不是很C++y(?

in指的是std::array<unsigned long long int, 3>std::array<unsigned long long int, 3>{1,1,1}也是一个std::array<unsigned long long int, 3>,因此你可以通过==直接比较它们:

if(in == std::array<unsigned long long int, 3>{1,1,1})

如果数组具有更多元素,您可能希望使用算法来避免创建第二个数组。大致如下(未测试(:

if (in.end() == std::find_if(in.begin(),in.end(),[](auto x){ return x != 1; }))

如果只有三个元素,我可能会简单地写

if (in[0] == 1 && in[1] == 1 && in[2] == 1)

相关内容

最新更新