【发布时间】:2018-04-15 06:25:30
【问题描述】:
所以我试图确定一个相同值的数组是否在堆栈中。
Stack<string> stackOfStrings = new Stack<string>();
stackOfStrings.Push("dog");
stackOfStrings.Push("cat");
Debug.WriteLine("stackOfString contains cat: " +
stackOfStrings.Contains("cat"));
Debug.WriteLine("stackOfString contains dog: " +
stackOfStrings.Contains("dog"));
Stack<int[]> stackOfIntArrays = new Stack<int[]>();
stackOfIntArrays.Push(new int[]{0,1});
stackOfIntArrays.Push(new int[]{1,1});
int[] array01 = new int[]{0,1};
int[] anotherArray01 = new int[]{0,1};
int[] array11 = new int[] { 1, 1 };
Debug.WriteLine("SequenceEqual can compare arrays of identical value: " + array01.SequenceEqual(anotherArray01));
Debug.WriteLine("SequenceEqual can be used to compare the top value of a stack: " + stackOfIntArrays.Peek().SequenceEqual(array11));
//I want the line below to evaluate to true
Debug.WriteLine("Contains can be used to determine if an array of values is within the stack: " + stackOfIntArrays.Contains(array01));
这是代码的输出:
stackOfString contains cat: True
stackOfString contains dog: True
SequenceEqual can compare arrays of identical value: True
SequenceEqual can be used to compare the top value of a stack: True
Contains can be used to determine if an array of values is within the stack: False
我对此的研究已经产生了很多结果,可以查看一个数组是在另一个数组中还是另一个数组的子集,这就是我了解 SequenceEqual 的方式。看到这似乎只能检查堆栈中的顶部值,这不足以满足我的要求。
我考虑过的另一种解决方案是将堆栈重新堆叠到一个新堆栈中,并在每个数组移动时检查它。但是,考虑到 contains 可以在整个堆栈中查找字符串类型的值,我得出的结论是,对于 int[] 类型的值应该是可能的。如果没有,我们将不胜感激有关最佳解决方法的指导。
【问题讨论】:
-
您想知道堆栈的任何元素是否序列等于特定值。这是否让您知道如何实施它?
-
如果你想让 Contains() 工作,那么你需要一个 IEqualityComparer,它的功能比默认的要多,它只检查对象身份。
标签: c# arrays stack contains any