2013-04-08 96 views
0

在下面的示例代码中,我需要将结构向量传递给函数。如何将结构向量传递给C++中的函数?

class A { 
public: 
    struct mystruct { 
     mystruct (int _label, double _dist) : label(_label), dist(_dist) {} 
     int label; 
     double dist; 
    }; 
} 

我声明如下矢量:

vector<A:: mystruct > mystry; 

现在,在这个 “A” 级有如下的功能。

myfunc (vector<mystruct> &mystry); 

如何将结构向量传递给我的“myfunc”?

+0

@nommyravian这个问题是关于传递载体,在我的情况下,其结构的载体? – 2vision2 2013-04-08 04:40:38

+2

这是关于矢量的东西。它们包含的内容并不重要。 – chris 2013-04-08 04:47:04

+0

你在哪里遇到问题?将一个向量传递给一个函数就像将其他任何东西传递给一个函数一样。 – juanchopanza 2013-04-08 05:43:10

回答

4

试试这个

#include <iostream> 
#include <vector> 

using namespace std; 

class A { 
public: 
    struct mystruct { 
     mystruct (int _label, double _dist) : label(_label), dist(_dist) {} 
     int label; 
     double dist; 
    }; 

    void myfunc (vector<mystruct> &mystry){ 
     cout << mystry[0].label <<endl; 
     cout << mystry[0].dist <<endl; 
    } 
}; 

int main(){ 
    A::mystruct temp_mystruct(5,2.5); \\create instance of struct. 

    vector<A:: mystruct > mystry; \\ create vector of struct 
    mystry.push_back(temp_mystruct); \\ add struct instance to vector 

    A a; \\ create instance of the class 
    a.myfunc(mystry); \\call function 
    system("pause"); 
    return 0; 
} 
+0

这似乎过于复杂。 OP仅询问如何将矢量传递给'myfunc'。 – anthropomorphic 2013-04-08 05:02:13

+0

@MichaelDorst - 1.这是一个工作示例,所以OP可以调试并获得想法。 2.我评论了OP需要理解并使程序易于理解的无力点。在这个简单的程序中,我没有看到任何复杂的内容,主要是从OPs代码中复制而来的。 =) – 2013-04-08 05:44:36

0

哦,首先你需要创建的A一个实例,像这样:

A a; 

然后,你需要调用myfunca,通过它的价值mystry

a.myfunc(mystry);