簡體   English   中英

在c ++中使用std :: vector的2d數組 - 容器

[英]2d array with std::vector in c++ - container

我試圖通過制作EdgeWeights的向量向量來創建一個二維數組(它用於鄰接矩陣),但是我很難理解嵌套容器的運行方式。

我正在構建前面提到的結構,

std::vector<std::vector<EdgeWeight> > M = 
    std::vector<std::vector<EdgeWeight>>(num_edges, std::vector<EdgeWeight>(num_nodes));

但我很難理解發生了什么。 為什么參數會按順序進行? 此外,一旦創建它我不明白如何訪問容器的元素。 這是如何運作的?

編輯:我想在鄰接矩陣中添加邊緣權重是這個

M.at(u).at(v) = weight; //M is the matrix.

模板類std::vector具有以下構造函數

explicit vector(size_type n, const T& value, const Allocator& = Allocator());
explicit vector(size_type n, const Allocator& = Allocator());

第一個構造函數允許定義一個對象,該對象包含最初由value初始化的n元素

而不是定義

std::vector<std::vector<EdgeWeight> > M = 
    std::vector<std::vector<EdgeWeight>>(num_edges, std::vector<EdgeWeight>(num_nodes));

你可以寫簡單

std::vector<std::vector<EdgeWeight> > M( num_edges, std::vector<EdgeWeight>(num_nodes) );

因此,在此定義中,您將創建包含std::vector<EdgeWeight>類型的num_edges元素的對象Mnum_edges元素由std::vector<EdgeWeight>(num_nodes)初始化。 也就是說,每個元素依次是使用第二個構造函數創建的num_nodes元素的向量。

您可以將此想象為創建具有num_edges行和num_nodes列的矩陣。 只有每一行都是std::vector<EdgeWeight>類型的對象,你需要為它調用一個構造函數來指定必須在行中創建多少列。

我真的不明白你在做什么但是

std::vector<std::vector<EdgeWeight> > M

這是一個2d向量,可以包含另一個類型為EdgeWeight的向量,即

std::vector<EdgeWeight> N;  
N.push_back(this value here is passed to the constructor of you EdgeWeight class);  

接着:

M.push_back(N);

暫無
暫無

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

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