在头文件中声明和初始化一个向量
declaring and initialising a vector in the header file
在我的条目 cpp 文件中,以下工作。
include <vector>
#define ROWS 10
#define COLS 20
std::vector<std::vector<int>> exampleVector (ROWS, std::vector<int>(COLS, 10));
但是,如果我将相同的代码放入我的 example.h 文件中,我会得到
- "expected a type specifier" 在 ROWS
- "expected a ')'" 上 COLS
- "expected a type specifier" 10
- “期望';'在第二个)
我知道我可以把
std::vector<std::vector<int> exampleVector;
在我的 example.h 文件和
exampleVector.resize(ROWS, std::vector<int>(COLS, 10));
在我的 example.cpp 文件中。
但是为了代码的整洁,我希望它与我的固定数组一起出现在我的头文件中。
char exampleName[MAX_NAME_LENGTH]
int exampleConfig[MAX_LEVELS]
等等
您的示例代码有问题(关闭 >
丢失?)但忽略它,答案是:无法在定义时指定 std::vector
的大小.
另一方面,std::array
的大小可以是:
#include <array>
#define ROWS 10
#define COLS 20
std::array<std::array<int, ROWS>, COLS> exampleArray;
在我的条目 cpp 文件中,以下工作。
include <vector>
#define ROWS 10
#define COLS 20
std::vector<std::vector<int>> exampleVector (ROWS, std::vector<int>(COLS, 10));
但是,如果我将相同的代码放入我的 example.h 文件中,我会得到
- "expected a type specifier" 在 ROWS
- "expected a ')'" 上 COLS
- "expected a type specifier" 10
- “期望';'在第二个)
我知道我可以把
std::vector<std::vector<int> exampleVector;
在我的 example.h 文件和
exampleVector.resize(ROWS, std::vector<int>(COLS, 10));
在我的 example.cpp 文件中。
但是为了代码的整洁,我希望它与我的固定数组一起出现在我的头文件中。
char exampleName[MAX_NAME_LENGTH]
int exampleConfig[MAX_LEVELS]
等等
您的示例代码有问题(关闭 >
丢失?)但忽略它,答案是:无法在定义时指定 std::vector
的大小.
另一方面,std::array
的大小可以是:
#include <array>
#define ROWS 10
#define COLS 20
std::array<std::array<int, ROWS>, COLS> exampleArray;