为什么字典“未排序"? [英] Why is a Dictionary "not ordered"?

查看:36
本文介绍了为什么字典“未排序"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读本文以回答此处的许多问题.但这究竟是什么意思?

I have read this in answer to many questions on here. But what exactly does it mean?

var test = new Dictionary<int, string>();
test.Add(0, "zero");
test.Add(1, "one");
test.Add(2, "two");
test.Add(3, "three");

Assert(test.ElementAt(2).Value == "two");

上面的代码似乎按预期工作.那么字典以何种方式被认为是无序的呢?上面的代码在什么情况下会失败?

The above code seems to work as expected. So in what manner is a dictionary considered unordered? Under what circumstances could the above code fail?

推荐答案

嗯,有一点不清楚你希望这是插入顺序还是键顺序em>.例如,如果您这样写,您希望结果是什么:

Well, for one thing it's not clear whether you expect this to be insertion-order or key-order. For example, what would you expect the result to be if you wrote:

var test = new Dictionary<int, string>();
test.Add(3, "three");
test.Add(2, "two");
test.Add(1, "one");
test.Add(0, "zero");

Console.WriteLine(test.ElementAt(0).Value);

您希望三"还是零"?

碰巧的是,我认为当前的实现会保留插入顺序,只要您从不删除任何内容 - 但您不能依赖于此.这是一个实现细节,将来可能会发生变化.

As it happens, I think the current implementation preserves insertion ordering so long as you never delete anything - but you must not rely on this. It's an implementation detail, and that could change in the future.

删除也会影响这一点.例如,您希望这个程序的结果是什么?

Deletions also affect this. For example, what would you expect the result of this program to be?

using System;
using System.Collections.Generic;

class Test
{ 
    static void Main() 
    {
        var test = new Dictionary<int, string>();
        test.Add(3, "three");
        test.Add(2, "two");
        test.Add(1, "one");
        test.Add(0, "zero");

        test.Remove(2);
        test.Add(5, "five");

        foreach (var pair in test)
        {
            Console.WriteLine(pair.Key);
        }
    }     
}

实际上(在我的盒子上)是 3、5、1、0.5 的新条目使用了 2 之前使用的空条目.不过这也不能保证.

It's actually (on my box) 3, 5, 1, 0. The new entry for 5 has used the vacated entry previously used by 2. That's not going to be guaranteed either though.

重新散列(当字典的底层存储需要扩展时)可能会影响事情......各种各样的事情都会发生.

Rehashing (when the dictionary's underlying storage needs to be expanded) could affect things... all kinds of things do.

只是不要将其视为有序集合.它不是为此而设计的.即使它现在碰巧起作用,您也依赖于违背课程目的的无证行为.

这篇关于为什么字典“未排序"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆