2016-06-07 80 views
-3

我试图创建一个结构的向量。我在创建带有结构的向量时遇到了一些问题。向量的结构

这里的错误消息:

testt.cpp: In constructor 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Al 
loc>::size_type, const value_type&, const allocator_type&) [with _Tp = flowPath; 
_Alloc = std::allocator<flowPath>; std::vector<_Tp, _Alloc>::size_type = unsign 
ed int; std::vector<_Tp, _Alloc>::value_type = flowPath; std::vector<_Tp, _Alloc 
>::allocator_type = std::allocator<flowPath>]': 
testt.cpp:20:28: error: no matching function for call to 'flowPath::flowPath()' 
testt.cpp:20:28: note: candidates are: 
testt.cpp:10:5: note: flowPath::flowPath(int) 
testt.cpp:10:5: note: candidate expects 1 argument, 0 provided 
testt.cpp:5:8: note: flowPath::flowPath(const flowPath&) 
testt.cpp:5:8: note: candidate expects 1 argument, 0 provided 

下面的代码:

#include <vector> 
#include "FlowGraph.cpp" 
using namespace std; 

struct flowPath { 
    int vertex; 
    Edge *edge; 
    Edge *res; 

    flowPath(int v){ 
     vertex = v; 
    } 
}; 

void bfs(vector<flowPath>& parentPath){ 
    //Stuffs 
} 

int main(void) { 
    vector<flowPath> path(5); 
    bfs(path); 
    return 0; 
} 

我没有得到一半的错误,我尝试了谷歌的东西,但失败了.. 。 提前致谢!

+2

'VECTOR'需要的类型('flowpath') – Ajay

+0

通知了'错误默认的构造函数:'一部分。地点和笔记后来。 – LogicStuff

+0

我有一个构造函数,flowpath(int v){}? – Sakutard

回答

1

您需要flowPath一个默认的构造如下(例如,可以做不同的课程):

struct flowPath { 
    int vertex; 
    Edge* edge; 
    Edge* res; 

    flowPath() : vertex(0), edge(nullptr), res(nullptr) {} 

    //... 
}; 

然后,您可以在std::vector中使用flowPath。或者,如果您不想在flowPath中使用默认构造函数,则可以使用std::vector<std::unique_ptr<flowPath>>(您也可以使用std::vector<flowPath*>,但使用智能指针更符合现代C++)。

+0

将“flowpath(){}”作为默认构造函数吗? – Sakutard

+0

@Sakutard从技术上来说,是的,但是这意味着'flowPath'的字段不会被初始化为任何可能导致问题的东西,如果您尝试访问它们而不设置它们。 – ArchbishopOfBanterbury

+0

我试图让我的结构“flowPath fp = new flowPath(0)”的新对象,但得到错误 “从'flowPath *'无效转换为'int'[-fpermissive] 初始化参数1' flowPath :: flowPath(int)'[-fpermissive]“。为什么? – Sakutard

0

本声明:

vector<flowPath> path(5); 

未通过5flowpath构造,只是到vector。这里的值5表示为5个元素分配和保留内存。 vector需要类型(您的案例中的flowpath)具有可访问的默认构造函数。

您可能必须flowpath类的默认构造函数,或使参数默认:

flowPath(int v = 1){ 
     vertex = v; 
    } 
+0

是的,我明白了,我只是想让这个矢量变得那么大。 – Sakutard

0

你可以试试这个:

struct flowPath { 
    int vertex; 
    Edge *edge; 
    Edge *res; 
    flowPath(int v){ 
     vertex = v; 
    } 
}; 

void bfs(vector<struct flowPath>& parentPath){ 
    //Stuffs 
} 

int main(int argc, char *argv[]) { 
    vector<struct flowPath> path(1,5); /*One vector of dimension 1 will be created, and the value of 5 will be passed to the constructor*/ 
    //bfs(path); 
    return 0; 
} 
+0

尽管此代码片段可能会解决问题,但[包括解释](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性注释来挤占代码,这会降低代码和解释的可读性! –