2012-01-08 4 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テンプレートは、通常、含まれるデータのタイプを決定する1つのパラメータのみをとります(また、常に固定数のパラメータがあります)。

あなたが構造

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を作成し、この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の詳細については、上記のリンクをクリックしてください。

関連する問題