C++ 可能 #define 一些东西但之前使用过

C++ possible #define something but used before

我想知道这是否可行(为了在项目中非常容易使用)

说:

// array size (COUNT)
int foo[COUNT];

// values
foo[0] = 1;
foo[1] = 43;
foo[2] = 24;

// define (or equivalent) its size at the end
#define COUNT 3    

(这是设计使然,因此我不必在每次更改数组长度时都对其进行微调)

谢谢。

编辑: 我正在寻找的是在用值填充后定义数组的大小。在这个例子中,我只知道当我输入值时它是 3。所以我可以再添加 4 个 "foo",只需要更改下面的 #define。

下一次编辑:

// this is the idea, can this be possible? or even a "forward" declared
int foobar = THEVALUE

// way further down
#define THEVALUE 5;
int foo[] = {1, 43, 24};
int const count = 3;    // See the SO array FAQ for how to compute this.

一种简单的类型安全计算大小的方法,在 SO 数组常见问题解答中没有提到(因为它是在 C++11 之前编写的)

int const count = end( foo ) - begin( foo );

其中 endbegin<iterator> header.

中的 std 命名空间函数

其他方法见SO array FAQ


通常,在现代 C++ 中,最好使用 std::array(固定大小)和 std::vector(动态大小)而不是原始数组。这更安全,功能更丰富,特别是分配和轻松检查大小的能力。不幸的是 std::array 不支持从初始值设定项推断出的大小,因此即使数组大小是常量,您也必须使用 std::vector

vector<int> foo = {1, 43, 24};

// foo.size() gives you the size at any moment.

你可以用初始化列表初始化数组,然后你根本不需要知道它的大小:

int foo[] = { 1, 43, 24 }
int size = sizeof(foo) / sizeof(int); // if you do need to know size

编辑: 对于更惯用的 C++11,请参阅上面的答案:)