std::vector size in header

2019-06-11 16:52发布

I have small question about std::vector. In main.h i try to make fixed size int vector

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

But g++ gived this error:

../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);
}

标签: c++ vector std
2条回答
叛逆
2楼-- · 2019-06-11 17:12

Assuming foo is a data member, your syntax is invalid. In general, you can initialize a data member of type T like this:

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> foo = std::vector<int>(7);

If you are stuck with a pre-C++11 compiler, you would need to use a constructor:

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

and take care to initialize the vector in all constructors (if applicable.)

查看更多
Evening l夕情丶
3楼-- · 2019-06-11 17:20

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:

(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)

file.h:

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

file.cpp :

for(int i=0; i < YOURCLASSFOOSIZE; i++)
{
    foo.push_back(0);
}
查看更多
登录 后发表回答