在 c++ 中的类中定义具有固定大小的向量

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

本文关键字:向量 c++ 定义      更新时间:2023-10-16

以下是我的代码部分C++

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

评论中标记的行给了我错误:
expected identifier before numeric constant expected ‘,’ or ‘...’ before numeric constant

但是当我执行以下操作时,它可以编译而没有错误

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

我想通了,即使我只是在第一种方法中定义vector < vector<int> >edg它也可以正常工作,所以问题出在恒定大小51,我似乎不明白。我尝试谷歌搜索,但由于我的 oop 的概念很弱,我不太了解,谁能解释为什么会发生这种情况?

这是

定义类成员的限制。如果你想要一个固定大小的向量,只需使用std::array,这将允许你做到这一点。

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

或者,可以在构造函数中声明大小:

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

类内初始化只能使用 = 或大括号列表完成,不能使用 () 完成。由于vector使用大括号列表的行为不同,因此您需要使用 = .

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

或者以老式的方式在构造函数中初始化它。

MyClass() : edg(51) {}
以防

万一有人在C++类中初始化固定大小的向量时遇到问题,您可以这样做。

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