【问题标题】:Most efficient way to create multidimensional array of same chars? [C++]创建相同字符的多维数组的最有效方法? [C++]
【发布时间】:2015-07-05 07:47:22
【问题描述】:

对不起,如果这已在其他地方得到回答。我很新,不知道如何真正解释这样的问题。

现在,我正在寻求创建一个包含“+”字符的 [5]x[5] 数组。这是我所拥有的:

#include <iostream>
using namespace std;

int main() {
char map[5][5] = {{'+','+','+','+','+'},{'+','+','+','+','+'},{'+','+','+','+','+'},{'+','+','+','+','+'},{'+','+','+','+','+'}};

for (int x = 0; x < 5; x++) {
    for(int y = 0; y < 5; y++) 
        cout << map[x][y] << " ";
    cout << endl;
}

return 0;
}

有没有一种方法可以重复这些“+”字符而不必一遍又一遍地列出每个字符?

谢谢你:)

从长远来看,我希望创建一个 [n]x[n] 地图,作为一个有趣的学习项目,玩家可以在其中四处走动和互动。

【问题讨论】:

    标签: c++ arrays dictionary multidimensional-array repeat


    【解决方案1】:

    std::vector 的构造函数提供了一种简单的方法来轻松构造对象:

    #include <vector>
    //...
    std::size_t n = 5;
    std::vector<std::vector<char>> map(std::vector<char>('+', n), n);
    //If using Visual Studio 2012 (or equivalent) or earlier:
    std::vector<std::vector<char> > map(std::vector<char>('+', n), n);
    

    【讨论】:

    • 为了安全起见,您应该始终使用第二个,这不是 Visual Studio 的东西,它只在 C++11 标准中。
    • @meneldal 因此是“或等价物”:P
    【解决方案2】:

    如果你想要尽可能少的代码,怎么样:

    #include <string.h>
    memset(&map[0][0], 'x', sizeof(map));
    

    【讨论】:

    • 为什么不只是memset(map, 'x', sizeof(map));
    • @BillLynch 我相信memset 想要一个指针而不是一个双指针,所以你至少必须放像map[0]这样的东西
    • @meneldal map 可以隐式转换为 char(*)[5],其值仍指向 map[0][0]。所以我认为它应该有效。
    • 我认为 C++ 与 C 的不同之处在于,人们普遍认为隐式指针转换是邪恶的。这个问题的惯用 C++ 无论如何都会使用std::vector
    【解决方案3】:

    这很简单:只需做一个简单的循环:

    char map[5][5];
    for (int x = 0; x < 5; x++) {
        for(int y = 0; y < 5; y++) 
            map[x][y]='+';
    }
    

    【讨论】:

    • 欣赏 :) 也谢谢大家
    猜你喜欢
    • 2019-01-16
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多