结构的向量

时间:2016-06-07 19:58:09

标签: c++ vector struct

我试图创建一个结构的向量。使用struct创建向量时遇到一些问题。

以下是错误消息:

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

我没有收到错误的一半,而且我已经尝试过谷歌但却失败了...先谢谢!

3 个答案:

答案 0 :(得分:1)

您需要flowPath的默认构造函数,如下所示(例如,当然可以采用不同的方式):

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

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

    //...
};

然后,您可以在flowPath中使用std::vector

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

答案 1 :(得分:0)

本声明:

vector<flowPath> path(5);

不会将5传递给flowpath的构造函数,而只传递给vector。这里的值5表示为5个元素分配和保留内存。 vector需要类型(在您的情况下为flowpath)才能访问默认构造函数。

您可能需要在flowpath类中使用默认构造函数,或将参数设为默认值:

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

答案 2 :(得分: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;
}
相关问题