简体   繁体   中英

std::vector size in header

I have small question about std::vector. In main.hi 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);
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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