當前位置:成語大全網 - 新華字典 - C++ 中Iterator與C#中的KeyValuePair

C++ 中Iterator與C#中的KeyValuePair

.Net已經幫妳封裝了叠代器,集合可以用foreach遍歷,

比C++的叠代器好用太多了···

比如C#字典類(.Net的哈希表的壹種叫法),

var dict = new Dictionary<string, int> {

{ "Apple", 1 }, { "Orange", 2 }, { "Banana", 3 }

};

foreach( KeyValuePair<string, int> i in dict ) // 這裏的KeyValuePair可用var替換

{

Console.WriteLine( i.Key + " : " + i.Value );

}

// 運行結果:

// Apple : 1

// Orange : 2

// Banana : 3

補充:

大概明白妳的意思了,使用叠代器的MoveNext方法就行了

// 取得字典的叠代器(枚舉器)

var enumerator = dict.GetEnumerator();

// 輸出當前的項,每壹項都是壹個KeyValuePair<string, int>

Console.WriteLine(enumerator.Current);

// 輸出下壹項

Console.WriteLine(enumerator.MoveNext());