2013-11-01 149 views
1

我有這樣的結構初始化用戶的矢量的矢量定義

struct myStruct { 
    int a; 
    int b; 
    } 

我想創建一個vector <vector<myStruct> > V並將其初始化類型的n空載體vector<myStruct>

我試圖使用在fill constructor 這樣的:

vector<edge> temp; 
vector<vector<edge> > V(n, temp); 

此代碼工作正常main,但是當我在一個類裏面有V時,我該如何在類構造函數中做到這一點。

編輯: 當我在我的類的構造函數,我得到以下錯誤:
no match for call to '(std::vector<std::vector<edge> >) (int&, std::vector<edge>&)'

代碼生成的錯誤是:

vector<myStruct> temp; 
V(n, temp); // n is a parameter for the constructor 
+1

使用初始化程序列表。 – Kunal

回答

3

首先,請注意temp是沒有必要:你的代碼是相同的

vector<vector<edge> > V(n); 

我們您的主要問題:當你的載體在類內部,如果成員是非靜態的,則使用初始化器列表,或者如果聲明部分是靜態的,則初始化聲明部分中的成員。

class MyClass { 
    vector<vector<edge> > V; 
public: 
    MyClass(int n) : V(n) {} 
}; 

或像這樣:

// In the header 
class MyClass { 
    static vector<vector<edge> > V; 
    ... 
}; 

// In a cpp file; n must be defined for this to work 
vector<vector<edge> > MyClass::V(n); 
+0

萬一我不能使用初始化列表? 我的構造函數需要一個文件,讀取數據,然後需要初始化, 我該怎麼做? –

+1

@ Mhd.Tahawi如果你不能使用初始化列表,你可以在構造函數體內使用一個賦值:'MyClass(int n){V = vector >(n); }' – dasblinkenlight

2

只是省略temp。在類的構造函數是V裏面應該是這樣的:

MyClass(size_t n) : V(n) {} 
0
class A 
{ 
private: 
    std::vector<std::vector<myStruct>> _v; 
public: 
    A() : _v(10) {} // if you just want 10 empty vectors, you don't need to supply the 2nd parameter 
    A(std::size_t n) : _v(n) {} 
    // ... 
}; 

您使用初始化列表對於這種初始化。