6.2 Arrays (Part II)

原完整教程链接:6.2 Arrays (Part II)

1.
// Initialize all elements to 0
int array[5] = { }; 

2.
// Enum classes don’t have an implicit conversion to integer, 
// however standard Enum does.
// So, how to solve this?
//** Use a standard enum inside of a namespace!**
namespace StudentNames
{
    enum StudentNames
    {
        KENNY, // 0
        KYLE, // 1
        STAN, // 2
        BUTTERS, // 3
        CARTMAN, // 4
        WENDY, // 5
        MAX_STUDENTS // 6
    };
}
 
int main()
{
    int testScores[StudentNames::MAX_STUDENTS]; // allocate 6 integers
    testScores[StudentNames::STAN] = 76;
}

3.
Although passing an array to a function at first glance looks just like 
passing a normal variable, underneath the hood, C++ treats arrays differently.

When a normal variable is passed by value, C++ copies the value 
of the argument into the function parameter. Because the parameter 
is a copy, changing the value of the parameter does not change the 
value of the original argument.

However, because copying large arrays can be very expensive, 
C++ does not copy an array when an array is passed into a 
function. Instead, the actual array is passed. This has the side effect 
of allowing functions to directly change the value of array elements!

4.
// Determining the length of a fixed array
int main()
{
    double arr[9] = {};
    int length_of_arr = sizeof(arr) / sizeof(arr[0]);  // <-- Just this line!
    for (int i = 0; i < length_of_arr; i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,368评论 25 708
  • 这里十二年,终于要拆了,没有一丝怀念。 前一天还有人阿谀奉承地金总金总地叫着,在灯红酒绿中虚荣地应付自如。华丽的大...
    昀果阅读 175评论 0 0
  • 通过在新梦想学习后,说实话,真的有收获的!今天早上我去竞聘领班感觉没有那么紧张了,这些日子忙得头晕脑胀的,药监局要...
    参天大树_daa9阅读 187评论 0 0
  • 从官网下载安装包,按照默认配置将Android Studio安装完毕 新建一个Android Project,第一...
    jiaozi0203阅读 950评论 0 0