首页 > 解决方案 > 为什么 C++ 中的数组和向量之间的字节大小存在差异?

问题描述

我正在学习 C++ 初学者课程,我想暂停课程并修改我正在学习的代码。我有在 C++ 中对向量和数组使用 sizeof() 运算符的想法。最终发现向量和数组中的数字数量相同,它们的字节大小不同。这是我的代码。

#include <iostream>
#include <vector>


int main()  {

   std::vector <int> test_scores { 100,99,90,70,75 };

   int test_scores_array[]{ 100,99,90,70,75 };

   std::cout << sizeof(test_scores) << std::endl;
   std::cout << sizeof(test_scores_array) << std::endl;

   return 0;
}

输出这个

16
20

在谷歌搜索大约 30 分钟后,我无法弄清楚为什么大小不同。我并不是真的“需要”知道,但我只是觉得它与众不同并且真的很想知道为什么真的很有趣。

标签: c++arraysvectorsizeof

解决方案


推荐阅读