【问题标题】:2d array with std::vector in c++ - containerc++ 中带有 std::vector 的二维数组 - 容器
【发布时间】:2015-05-10 07:18:13
【问题描述】:

我正在尝试通过制作 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.

【问题讨论】:

  • “我猜想在邻接矩阵中添加边权是这样的” 它是否有效?或者你可以写:M[u][v] = weight;

标签: c++ vector graph containers


【解决方案1】:

模板类std::vector有如下构造函数

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

第一个构造函数允许定义一个包含n元素的对象,该元素最初由value初始化

代替定义

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) );

因此,在此定义中,您创建对象M,其中包含由std::vector&lt;EdgeWeight&gt;(num_nodes) 初始化的std::vector&lt;EdgeWeight&gt; 类型的num_edges 元素。也就是说,每个元素依次是使用第二个构造函数创建的num_nodes 元素的向量。

您可以将其想象为创建一个包含num_edges 行和num_nodes 列的矩阵。只有每一行是std::vector&lt;EdgeWeight&gt; 类型的对象,您需要为其调用构造函数来指定必须在该行中创建多少列。

【讨论】:

    【解决方案2】:

    我不是很明白你在做什么,但是

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

    这里是一个二维向量,可以包含另一个 EdgeWeight 类型的向量,即

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

    然后:

    M.push_back(N);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 2018-07-02
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      相关资源
      最近更新 更多