简体   繁体   English

标题中的std :: vector大小

[英]std::vector size in header

I have small question about std::vector. 我对std :: vector有一个小问题。 In main.hi try to make fixed size int vector 在main.hi中尝试使用固定大小的int向量

std::vector<int> foo(7);

But g++ gived this error: 但是g ++给出了这个错误:

../test/main.h:21:26: error: expected identifier before numeric constant
 std::vector<int> foo(7);
../main/main.h:21:26: error: expected ',' or '...' before numeric constant

How can i create private vector variable of fixed size length? 如何创建固定大小长度的私有向量变量? Or should i simply make in constructor 或者我应该简单地在构造函数中

for(int i=0; i<7;i++){
    foo.push_back(0);
}

Assuming foo is a data member, your syntax is invalid. 假设foo是数据成员,则语法无效。 In general, you can initialize a data member of type T like this: 通常,您可以像这样初始化类型为T的数据成员:

T foo{ctor_args};

or this 或这个

T foo = T(ctor_args);

However, std::vector<int> has a constructor that takes an std::initializer_list<int> , which means that the first form would yield a size-1 vector with a single element of value 7. So you are stuck with the second form: 但是, std::vector<int>有一个带有std::initializer_list<int>的构造std::initializer_list<int> ,这意味着第一个表单将产生一个带有单个元素值为7的size-1向量。所以你坚持使用第二种形式:

std::vector<int> foo = std::vector<int>(7);

If you are stuck with a pre-C++11 compiler, you would need to use a constructor: 如果你坚持使用pre-C ++ 11编译器,则需要使用构造函数:

class bar
{
public:
    bar() : foo(7) {}
private:
  std::vector<int> foo;
};

and take care to initialize the vector in all constructors (if applicable.) 并注意在所有构造函数中初始化向量(如果适用)。

The most efficient way to initialize a class member (other than built-in type), is to use the initialisation list. 初始化类成员(除了内置类型)的最有效方法是使用初始化列表。

So the best solution here, is to construct your vector of length 7 in the initilization list of your class constructor: 所以这里最好的解决方案是在类构造函数的启动列表中构造长度为7的向量:

(I also recommend you to use a define for your fixed value 7. If you change it to 8 in the futur your will not have to change the value 7 on all your code) (我还建议您使用定义作为固定值7.如果在未来中将其更改为8,则不必更改所有代码中的值7)

file.h: file.h:

#define YOURCLASSFOOSIZE 7
class yourClass
{
public:
    yourClass(): foo(YOURCLASSFOOSIZE) {}
private:
    std::vector<int> foo;
};

file.cpp : file.cpp:

for(int i=0; i < YOURCLASSFOOSIZE; i++)
{
    foo.push_back(0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM