sách gpt4 ăn đã đi

c# - 数组比较作为 C# 中的字典键

In lại 作者:太空狗 更新时间:2023-10-30 01:09:18 25 4
mua khóa gpt4 giày nike

我想创建表示 n 维数组的类,但其中是对其元素的可交换访问。例如:a[new[] {4, 7, 55}] == a[new[] {55, 4, 7}]

我编写这段代码,我在其中实现接口(interface) IEqualityComparer 以便根据键(数组)的实际内容而不是引用来比较它们。

sử dụng Hệ thống;
sử dụng System.Collections.Generic;
sử dụng System.Linq;

class NArray
{
public int this[int[] x]
{
lấy
{
Array.Sort(x);
return array[x];
}
bộ
{
Array.Sort(x);
array[x] = value;
}
}

public void Remove(int[] x)
{
Array.Sort(x);
array.Remove(x);
}

Dictionary array = new Dictionary(new ArrCmpr());
}

class ArrCmpr : IEqualityComparer
{
public bool Equals(int[] a, int[] b)
{
return a.Length == b.Length && Enumerable.Range(0, a.Length).All(i => a[i] == b[i]);
}

public int GetHashCode(int[] a)
{
return a.GetHashCode();
}
}

但是当我开始使用这个类时,我遇到了一个异常:“System.Collections.Generic.KeyNotFoundException:字典中不存在给定的键。”当我尝试将元素输出到控制台时,接下来的两种情况都会发生此异常:

NArray a = new NArray();
a[new[] { 1, 3, 2 }] = 4;

Console.WriteLine(a[new[] { 3, 2, 1 }]);//错误

NArray b = new NArray();
b[new[] { 1, 2, 3 }] = 4;
Console.WriteLine(b[new[] { 1, 2, 3 }]); //error

那么这个问题的原因是什么,我该如何解决呢?

câu trả lời hay nhất

那是因为您对 GetHashCode 的实现不正确:具有相同顺序的相同项目的两个不同数组通常不会具有相同的哈希码(因为没有考虑值),所以Equals 永远不会被调用。

您需要一个将数组中的值考虑在内的 GetHashCode hoàn thành:

class ArrCmpr : IEqualityComparer
{
public bool Equals(int[] a, int[] b)
{
return a.SequenceEqual(b);
}

public int GetHashCode(int[] a)
{
return a.Aggregate(0, (acc, i) => unchecked(acc * 457 + i * 389));
}
}

关于c# - 数组比较作为 C# 中的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7138382/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress