2012-01-08 24 views
1

我想要使用三個字段的數組(長度爲count) - 長度爲a,長度爲9的int向量名爲b和布爾型c如何正確地聲明這個向量?

什麼是正確的方式來聲明它?

宣言1:

vector <long a, vector<int> b(9), bool c> matrix(count); 

錯誤:

code.cpp: In function ‘int main()’: 
code.cpp:89:49: error: template argument 1 is invalid 
code.cpp:89:49: error: template argument 2 is invalid 
code.cpp:89:57: error: invalid type in declaration before ‘(’ token 

宣言2:

vector <long, vector<int>, bool> matrix(count, a, vector<int> b(9), c); 

錯誤:

code.cpp: In function ‘int main()’: 
code.cpp:90:40: error: wrong number of template arguments (3, should be 2) 
/usr/include/c++/4.5/bits/stl_vector.h:170:11: error: provided for ‘template<class _Tp, class _Alloc> class std::vector’ 
code.cpp:90:48: error: invalid type in declaration before ‘(’ token 
code.cpp:90:56: error: ‘a’ was not declared in this scope 
code.cpp:90:71: error: expected primary-expression before ‘b’ 
code.cpp:90:77: error: ‘c’ was not declared in this scope 
code.cpp:90:78: error: initializer expression list treated as compound expression 

我是STL的新手,不確定這裏的正確語法是什麼?

+1

我不清楚你正在做什麼,但如果你想在每個對象中有3個字段,那麼你將不得不創建一個結構,並且將這3個字段作爲成員,然後將結構的對象存儲在向量。 – 2012-01-08 13:32:54

回答

2

STL模板通常只採用一個參數來確定包含數據的類型(並且總是有固定數量的參數)。

爲了讓你必須創建一個結構

struct s 
{ 
    long a; 
    std::vector<int> b; 
    bool c; 

    s(); // Declared default constructor, see below 
}; 

,創造s類型的對象向量的預期效果;

std::vector<s> matrix(count); 

爲了初始化包含在結構中的對象,您可以遍歷一個向量並手動分配它們,或者聲明一個默認構造器。

s::s() 
: b(9) // after the colon, you can pass the constructor 
// parameters for objects cointained in a structure. 
{ 
    a = 0; 
    c = false; 
} 
+0

並不總是有一個固定數量的tempalte參數,std :: tuple <...>是可變參數。 – Adrien 2013-09-03 11:28:07

2
struct Fields { 
    long a; 
    std::array<int, 9> b, 
    bool c; 
}; 

std::vector<Fields> matrix(count); 

std::vector<std::tuple<long, std::array<int, 9>, bool> > matrix(count); 
+0

在使用之前,我不需要在'Fields'上做'typedef'嗎? – Lazer 2012-01-08 13:49:44

+0

@拉澤爾:不,你不知道。 – 2012-01-08 16:17:48

1

有很多方法可以實現你想要什麼。其中之一是建立一個struct像下面並使用該struct創建std::vector<>

struct vector_elem_type 
{ 
    long a; 
    std::vector<int> b; 
    bool c; 
}; 

//vector of vector_elem_type 
std::vector< struct vector_elem_type > v(9); 

另一種方法是使用boost::tuple

// vector of tuples 
std::vector< boost::tuple< long, std::vector<int>, bool > v(9); 

// accessing the tuple elements  
long l = get<0>(v[0]); 
std::vector<int> vi = get<1>(v[0]); 
bool b = get<2>(v[0]); 

有關boost :: tuple的更多詳細信息,請單擊上面的鏈接。