2012-01-08 3 views
1

3 필드의 배열 (크기가 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 개의 필드를 멤버로 가지고 다음 구조체의 객체를 벡터. –

답변

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

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

+0

@Lazer : 아니에요. –

1

은 당신이 원하는 것을 달성하는 방법에는 여러 가지가 있습니다.

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을 사용하는 것입니다 그 중 하나는 다음과 같은 struct을 만들고이 struct 사용하여 std::vector<>을 만드는 것입니다.

// 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에 대한 자세한 내용은 위의 링크를 클릭하십시오.

관련 문제