dictionary<int,string>
时间: 2023-07-09 09:40:09 浏览: 36
这是一个 C++ 中的模板类,它表示一个键为整数,值为字符串的字典(或称为映射)。可以使用该类来存储整数和字符串之间的对应关系,例如:
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> dict;
dict[1] = "apple";
dict[2] = "banana";
dict[3] = "orange";
cout << dict[1] << endl; // 输出 "apple"
cout << dict[2] << endl; // 输出 "banana"
cout << dict[3] << endl; // 输出 "orange"
return 0;
}
```
在上面的例子中,我们先创建了一个空的 `map` 对象 `dict`,然后通过下标操作符 `[]` 向其中添加了三个键值对。最后,我们分别输出了键为 1、2、3 的对应的值。
相关问题
c# dictionary<int,string>
C# 中的 Dictionary 是一种键值对存储的数据结构,它将一个键(key)映射到一个值(value)。在这个例子中,我们定义了一个 Dictionary,其中键是 int 类型,值是 string 类型。这意味着我们可以使用整数作为键来访问字符串值。例如:
```
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Hello");
dict.Add(2, "World");
string value = dict[1];
Console.WriteLine(value); // 输出 "Hello"
```
Dictionary<int, string> 如何排序
你可以使用 LINQ 中的 OrderBy 方法对 Dictionary<int, string> 进行排序。下面是一个示例代码:
```csharp
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(3, "three");
dict.Add(1, "one");
dict.Add(2, "two");
var sortedDict = dict.OrderBy(x => x.Key);
foreach (var item in sortedDict)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
```
上述代码将按照字典键的升序对 Dictionary<int, string> 进行排序,并输出每个键值对。你可以根据需要调整排序方式,例如,使用 OrderByDescending 对键进行降序排序。