在 c++ 中的类中定义具有固定大小的向量
Defining a vector with fixed size inside a class in c++?
以下是我的代码部分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);
}
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么