2013-04-08 92 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);