C++ 如何在C++;?
我试着用3种不同的方法初始化一个2D向量,但总是得到一个C++ 如何在C++;?,c++,c++11,multidimensional-array,constructor,stdvector,C++,C++11,Multidimensional Array,Constructor,Stdvector,我试着用3种不同的方法初始化一个2D向量,但总是得到一个 "error: no matching function to call" 你能告诉我哪里错了吗 class Node { public: int to; int length; Node(int to, int length) : to(to), length(length){} }; class Graph { public: vector<vector<Node>> nodes_lis
"error: no matching function to call"
你能告诉我哪里错了吗
class Node
{
public:
int to;
int length;
Node(int to, int length) : to(to), length(length){}
};
class Graph
{
public:
vector<vector<Node>> nodes_list;
int n;
Graph();
};
Graph::Graph(){
nodes_list = vector<vector<Node> >(n, vector<Node>(n,0x3fffffff));
}
类节点
{
公众:
int到;
整数长度;
节点(int-to,int-length):to(to),length(length){
};
类图
{
公众:
向量节点列表;
int n;
图();
};
Graph::Graph(){
节点列表=向量(n,向量(n,0x3fffffff));
}
顺便说一下,我假设您使用了
名称空间std在图形的标题中添加code>,不要这样做,它会在某个时候给您带来问题。您的代码有两个问题:
在下一行中,您应该已经提供了
构造节点
,它们是到
和长度
vector<vector<Node>>(n, vector<Node>(n,0x3fffffff));
// ^^^^^^^^^^^--> here
还有一些建议:
使用
初始化向量,而不是创建并指定给它
同时命名构造函数参数和
在节点
中具有相同属性的成员。在某种程度上,这可能会导致
混乱
欢迎来到堆栈溢出。请阅读,采取,阅读,以及。最后,请学习如何创建一个。没有理由构建向量然后调整大小,在构建时初始化它可能会稍微更有效,就像OP所做的那样
vector<Node> v;
for ( size_t i = 0; i < n; i++ )
{
v.push_back(Node(0x3fffffff));
}
vector<Node>(n,Node(0x3fffffff,0));
vector<vector<Node>>(n, vector<Node>(n,0x3fffffff));
// ^^^^^^^^^^^--> here
struct Node
{
int _to;
int _length;
Node(int to, int length) : _to{ to }, _length{ length } {}
};
class Graph
{
using VecNode = std::vector<Node>; // type alias for convenience
private:
int _n;
std::vector<VecNode> _nodes_list;
public:
Graph()
: _n{ 2 } // initialize _n
, _nodes_list{ _n, VecNode(_n, { 1, 3 }) }
// ^^^^^^-> initialize with the default 'Node(1, 3)'
{}
};