如何比较数组的内容相等性
有没有办法让相等运算符用于比较相同类型的数组?
例如:
int x[4] = {1,2,3,4};
int y[4] = {1,2,3,4};
int z[4] = {1,2,3,5};
if (x == y) cout << "It worked!"
我知道它只是比较指针值 - 但我希望有某种 typedef 技巧或类似的东西,这样它就不需要循环或 memcmp 调用。
Is there a way to get the equality operators to work for comparing arrays of the same type?
For example:
int x[4] = {1,2,3,4};
int y[4] = {1,2,3,4};
int z[4] = {1,2,3,5};
if (x == y) cout << "It worked!"
I'm aware that as is, it's just comparing pointer values - but I was hoping there's some kind of typedef trick or something like that so it wouldn't need a loop or a memcmp call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用标准
std::equal
算法(或std::ranges::equal
自 C++20 起):You can use the standard
std::equal
algorithm (orstd::ranges::equal
since C++20):使用
std::equal
作为:它检查相同顺序的元素是否相等。这意味着,根据
std::equal
以下数组不相等。Use
std::equal
as:It checks equality of elements in the same order. That means, according to
std::equal
the following arrays are not equal.另一种方法是将数组包装在 std::array 模板中,这将为数组创建一个小型包装类。一切都与正常情况非常相似,只是您获得了
operator=
的默认定义,因此您可以正常使用==
来完成预期的操作。Another way would be to wrap your arrays in the
std::array
template, which will make a small wrapper class for the array. Everything works pretty much like normal, except that you get a default definition ofoperator=
, so you can use==
as normal to do the expected thing.由于数组具有相同的类型和长度,因此您可以使用 memcmp 来测试相等性,即值和位置相等:
Since the arrays are of the same type and length, you could use
memcmp
to test for equality, that is equality of value and position:解决方案 A - 使用
std::array
(C++11)std::array
一般可以避免很多 C 风格的数组问题,因此您可能需要用它替换所有对int[]
的使用。解决方案 B - 使用
std::span
s(C++20)std::span
是数组的轻量级非拥有视图。将范围包装在
std::span
中并使用==
运算符应该与使用标准库算法一样便宜。解决方案 C - 使用
std::equal
(C++98) 或std::ranges::equal
(C++ 20)Solution A - Use
std::array
(C++11)std::array
avoids a lot of C-style array problems in general, so you might want to replace all your uses ofint[]
with it.Solution B - Use
std::span
s(C++20)std::span
is a lightweight non-owning view into an array.Wrapping a range in a
std::span
and using the==
operator should be just as cheap as using standard library algorithms.Solution C - Use
std::equal
(C++98) orstd::ranges::equal
(C++20)我认为这里值得注意的是,C++ 不允许在没有至少 1 个用户定义类型的情况下重载
operator==
。这将是一个“不错”的解决方案,但即使可以,这也可能是一个坏主意。 C++ 中的数组...是一种邪恶的林地生物。std::equal
可能是您最好的选择。虽然你可能可以用 *gasp* 宏来做你想做的事,但我认为这很古怪。I think its also useful to note here that C++ does not allow you to overload
operator==
without at least 1 user-defined type. That would be the "nice" solution, but even if you could, it would probably be a bad idea. Arrays in C++...are sort of evil woodland creatures.std::equal
is probably your best bet. Though you could probably do what you want with a *gasp* macro, i think that is gacky.