advocateofnone
advocateofnone

Reputation: 2541

Defining a vector with fixed size inside a class in c++?

Following is the part of my code in C++

class Myclass 
{
    public:
       vector< vector<int> >edg(51); // <--- This line gives error
       // My methods go here
};

The line marked in the comments gives me the errors :
expected identifier before numeric constant
expected ‘,’ or ‘...’ before numeric constant

But when I do the following it compiles without errors

  vector< vector<int> >edg(51); // Declaring globally worked fine
  class Myclass 
  {
    public:
       // My methods go here
  };

I figured it out that even if I just define vector < vector<int> >edg in first method it works fine, so the problem is with the constant size 51, which I don't seem to understand. I tried googling but as my oop's concept are weak I did not understand much, could anyone explain why does this happen ?

Upvotes: 3

Views: 3307

Answers (3)

MohitHustler
MohitHustler

Reputation: 71

Just in case anyone is having the problem of initialising a fixed size vector inside a class in C++ , you can do this.

class DSU{
 vector<int> rank;
 public:
 DSU(int n){
 rank.resize(n);
 }

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254461

In-class initialisation can only be done with = or a brace-list, not with (). Since vector behaves differently with a brace-list, you'll need to use =.

vector< vector<int> > edg = vector< vector<int> >(51);

or initialise it in the constructor(s) in the old-fashioned manner.

MyClass() : edg(51) {}

Upvotes: 7

Luchian Grigore
Luchian Grigore

Reputation: 258588

It's a limitation wrt. defining class members. If you want a fixed-size vector, just use std::array instead, which will allow you to do exactly that.

class Myclass 
{
    public:
       array< vector<int>, 51 >edg; 
};

Alternatively, you can declare the size in the constructor:

class Myclass 
{
    public:
       vector< vector<int> >edg; 
       Myclass() : edg(51) {}
};

Upvotes: 9

Related Questions