Home > front end >  how can i initialize a bi-dimensional vector in a class in C ?
how can i initialize a bi-dimensional vector in a class in C ?

Time:07-16

I need to define its size in runtime, so I need a vector. I tried the following, but I get a compiling error:

error: 'V' is not a type

#include<iostream>
#include<vector>

class graph {
private:
    int V;
    std::vector<int> row(V);
    std::vector<std::vector<int>> matrix(V,row);
public:
    graph(int v): V(v) {}
};

Is there something I am failing to understand? Is it even allowed to initialize a vector this way?

CodePudding user response:

The compiler considers these lines:

std::vector<int> row(V);
std::vector<std::vector<int>> matrix(V,row);

as member function declarations with parameters that have unknown types and omitted names.

It seems what you need is to use the constructor's member initializer list instead, like the following:

class graph {
private:
    int V;
    std::vector<std::vector<int>> matrix;
public:
    graph(int v): V(v),  matrix( v, std::vector<int>( v ) ) {}
};
  • Related