std::vector size in header

风流意气都作罢 提交于 2019-12-08 07:04:30

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/29298026/stdvector-size-in-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!