簡體   English   中英

如何使用元組創建二維列表?

[英]How I can create 2d list with tuples?

我是 C# 的新手,現在我需要將 C++ 的代碼重寫為 C#。

std::vector<std::vector<std::pair<int, bool>>> board(n);
for (int i = 0; i < m; i++) 
{
    int node1 = 0, node2 = 0;
    std::cin >> node1 >> node2;
    board[node1 - 1].push_back(std::make_pair(node2 - 1, true));
    board[node2 - 1].push_back(std::make_pair(node1 - 1, false));
}

這是我的嘗試,但我無法創建具有指定長度的數組並將值添加到其中。

List<Dictionary<int, bool>> board = new List<Dictionary<int, bool>>();
        for (int i = 0; i < n; i++) board.Add(new List<Dictionary<int, bool>>);
        for (int i = 0; i < m; i++)
        {
            String[] road = Console.ReadLine().Split(' ');
            int node1 = int.Parse(road[0]), node2 = int.Parse(road[1]);
            board[node1 - 1].Add(Dictionary<int, bool>(node2 - 1, true));
            board[node2 - 1].Add(Dictionary<int, bool>(node1 - 1, false));
        }

c# 中std::vector的等價物是List<T> 對於元組,您可以在TupleValueTuple之間進行選擇。 所以你的類型可能是List<List<(int, bool)>>

您也可以考慮使用多維數組 (int, bool)[,]

您的 C++ 代碼分配一個 n 元素向量/向量列表/(int, bool)- 元組列表。 到 C# 的“逐字”翻譯將是List<List<(int, bool)>> ,或者使用 n 元素初始化,例如:

var board = Enumerable.Range(0, n).Select(i => new List<(int, bool)>()).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM