c++ - 在 C++ 中查找数组的大小

标签 c++ arrays size sizeof

通常,我会通过使用找到 double 组的大小

int size = sizeof(array_name)/sizeof(double)

但是,我使用名为“grades”的双数组作为名为“Grades”的类中的成员

class Grades{
    private:
        double grades[1024];

    public: Grades(string gradeList);
            Grades();

            int getNumGrades();
            string toString();
};

double 数组稍后在构造函数中填充。然而,当我这样做的时候

cout << "size = " << (sizeof(grades)/sizeof(double)) << endl;

它总是给我 1024。这是构造函数在填充了一些随机值后的末尾。我用 5 个值填充它。我怎样才能让它返回填充元素的数量?

最佳答案

我认为你应该有一个名为 elemInArray 的成员,它可以用这种方式实现。

class Grades{
    private:
        double grades[1024];
        unsigned int elemInArray;   // Note this

    public: Grades(string gradeList);
            Grades();

            int getNumGrades();
            string toString();
};

无论何时插入元素或从该数组中删除元素,您都可以递增和递减 elemInArray 以跟踪数组中的元素数量。

否则使用 STL 容器 ( http://en.cppreference.com/w/cpp/container )。

关于c++ - 在 C++ 中查找数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26814214/

相关文章:

c++ - 是否需要为每个线程或每个进程调用 srand() C 函数来为随机发生器设置种子?

c++ - 使用中间转换将 char* 缓冲区设置为 int*

python - 在 python 中计算大型 numpy 数组的速度和加速度

hadoop - 检索使用hadoop distcp复制的数据的大小

C++——向私有(private)成员字段 std::vector 添加元素

c - 如何在 C 代码中动态更改/伪造 'file size'

c++ - 没有 union 的哈希码的内存地址

c++ - 组合与继承——抽象类

arrays - 在 VBA 中仅粘贴二维数组的特定索引

c - 对于数组,为什么会出现 a[5] == 5[a]?