C++ 用常量值填充数组,循环和改变值

标签 c++ arrays loops constants

这是我正在编写的数组的一些基本代码。我需要用 4 填充数组的所有槽位 (14),然后编写一个循环将槽位 6 和 13 替换为 0。我是初学者,还没有学习 vector ,只是基本的编程 Material 。

const int MAX = 14;

int main ()
{

    board ();
    cout<<endl;

    {


        int i;
        int beadArray[MAX] = {4};

        for (i = 0; i < MAX; i++)
        {
            beadArray[i] = -1;
        }

        for (i = 0; i < MAX; i++)
        {
             cout<<i<<"\t";
        }
     }


    cout<<endl;
    system("pause");
    return 0;
}

最佳答案

#include <iostream>
#include <cstdlib>
using namespace std;

int main(){

    //this constant represents the size we want our array to be
    //the size of an array must be determined at compile time.
    //this means you must specify the size of the array in the code.
    const unsigned short MAX(14);

    //now we create an array
    //we use our MAX value to represent how large we want the array to be
    int beadArray[MAX] = {4};

    //now our array looks like this:
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //| 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    //but you want each index to be filled with 4.
    //lets loop through each index and set it equal to 4.
    for (int i = 0; i < MAX; ++i){
        beadArray[i] = 4;
    }

    //now our array looks like this:
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //| 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    //to set slots 6 and 13 equal to 0, it is as simple as this:
    beadArray[6] = 0;
    beadArray[13] = 0;

    //careful though, is that what you wanted?
    //it now looks like this:
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //| 4 | 4 | 4 | 4 | 4 | 4 | 0 | 4 | 4 | 4 | 4 | 4 | 4 | 0 |
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    //this is because the [index number] starts at zero.

    //index: 0   1   2   3   4   5   6   7   8   9   10  11  12  13
    //     +---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //     | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |
    //     +---+---+---+---+---+---+---+---+---+---+---+---+---+---+


    //print out your array to see it's contents:
    for (int i = 0; i < MAX; i++){
        cout << beadArray[i] << " ";
    }

    return EXIT_SUCCESS;
}

关于C++ 用常量值填充数组,循环和改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10309137/

相关文章:

c++ - 权重增加的枚举位集。 (C++ & Boost::dynamic_bitset)

Javascript 数组包含值

c++ - 返回到代码块的开头

loops - 无法使用 awk/gawk 循环多个输入文件

c++ - 使用 cmake 为 visual studio 构建 gtest

C++ XOR 加密/解密(异或密码)对我不起作用

c++ - 是否存在近似等同于运行时#ifdef 的C++ 编程技术?

javascript - Json 数组的输出值

javascript - 如何在javascript中不迭代的情况下查找数组中对象的索引

r - 如何在循环中使用 mutate 和 ifelse?