【问题标题】:Function that prints out a 2D string array [duplicate]打印出二维字符串数组的函数[重复]
【发布时间】:2021-03-17 18:52:12
【问题描述】:

我是 C++ 初学者

我一直在尝试制作一个打印出二维数组中所有元素的函数,但我无法完成这项工作,我需要一些帮助。

在我看来,我的 printArray 函数不能将二维数组作为有效的输入数据。 谁能给我一个建议?另外,是否有更好的方法来构建多维字符串数组而不使用 std::string?

感谢您的帮助!

int main ()
{
    
    std::string faces[5] = { "Pig", "sex", "John", "Marie", "Errol"};
    printArray(faces);

    std::string TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    //print2DArray(TwoD);
    
    std::cin.get();
    
}

void print2DArray(std::string x[])
{
    
    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
                    std::cout << x[i][j] << std::endl;
        
        }
    
}

【问题讨论】:

  • 无论何时使用 POA(普通旧数组),您都需要将数组中的元素数量作为参数与指针(或 C++ 中的引用)一起传递,以便函数知道有多少元素有。而是建议使用std::vector&lt;std::string&gt;,这样您就可以传递对向量的引用并使用.size() 成员函数来确定向量中字符串(元素)的数量。
  • 公平重复,但请参阅 Legends2k 的答案(其他一些答案完全值得怀疑)
  • @DavidC.Rankin 是的,它可能需要一个现代的答案。可能值得添加一个,甚至是悬赏。

标签: c++ arrays


【解决方案1】:

您必须为函数参数使用正确的类型(与要传递的数据匹配)。

此外,您必须在使用函数之前声明或定义函数。

#include <iostream>
#include <string>

void print2DArray(std::string x[][2]); // declare function

int main ()
{
    std::string TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    print2DArray(TwoD);
}

void print2DArray(std::string x[][2])
{

    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
            std::cout << x[i][j] << std::endl;
        
        }

}

如果您不打算修改字符串,使用const char* 可能是构建多维字符串数组而不使用std::string 的好方法。

#include <iostream>

void print2DArray(const char* x[][2]); // declare function

int main ()
{
    const char* TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    print2DArray(TwoD);
}

void print2DArray(const char* x[][2])
{

    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
            std::cout << x[i][j] << std::endl;
        
        }

}

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 2019-04-19
    • 2017-12-29
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多