如何正确声明此向量?

时间:2012-01-08 13:29:46

标签: c++ stl vector

我想使用三个字段的数组(大小为count) - 一个长a,一个长度为9的int向量b和一个bool 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的新手,我不确定这里的语法是什么?

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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);

答案 2 :(得分:1)

有很多方法可以达到你想要的效果。其中一个是创建struct,如下所示,并使用此std::vector<>创建struct

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的更多详细信息,请单击上面的链接。