使用C ++将一维数组转换为二维字符串数组

时间:2018-07-17 02:50:59

标签: c++ multidimensional-array

我一直在尝试将计数16(array [16])的数组创建为2D数组(array [4] [4])。

起初我有一个由50个字符串组成的数组:

    string housewives[50] = {"Vicki", "Tamra", "Shannon", "Kelly", "Peggy", "Heather", "Meghan", "Ramona", "Luann", "Bethenny", "Sonja", "Carole", "Dorinda", "Tinsley", "Alex", "Jill", "Kelly", "Aviva", "Heather", "Jules", "Nene", "Sheree", "Kandi", "Cynthia", "Kenya", "Porsha", "Kim", "DeShawn", "Lisa", "Phaedra", "Claudia", "Teresa", "Melissa", "Dolores", "Margaret", "Danielle", "Jacqueline", "Caroline", "Jacqueline", "Dina", "Siggy", "Kyle", "Erika", "Dorit", "Teddi", "Camille", "Taylor", "Adrienne", "Brandi", "Yolanda"};

然后我将其剥离到前8个:

    void stripArray(string array[8], size_t end) {
        for (int i=0; i<8; i++) {
            cout << array[i] << endl;
        }
        // this prints out "Ramona Yolanda Cynthia Nene Claudia Kandi Teddi Alex"
        setAnswerArray(array);
};

现在我需要将该数组加倍,以便有两个重复的单词:

    void setAnswerArray(string array[8]) {
        string *result = new string[8 + 8];
        copy(array, array + 8, result);
        copy(array, array + 8, result + 8);
        for (int i=0; i<16; i++) {
            cout <<result[i] << ' ';
        }
        //Now this prints out "Ramona Yolanda Cynthia Nene Claudia Kandi Teddi Alex Ramona Yolanda Cynthia Nene Claudia Kandi Teddi Alex"
};

然后如何将上述数组转换为4x4 2D数组?

我知道我需要使用for循环,这是到目前为止我尝试过的操作:

    string matrix[4][4];
    matricize(result, matrix, 4);

 void matricize(string list[16], string matrix[4][4], int rows)
{
    //INPUT THE VALUES OF ONE-DIMENSION ARRAY INTO THE TWO-DIMENSION ARRAY
    int listSize=0;

    for (int counter1 = 0; counter1 < rows; counter1++)
    {
        for (int count=0;count < 4; count++)
        {
            matrix[counter1][count] = list[listSize];
            listSize++;
        }
    }
    int width = 4, height = 4;
    for (width=0;width<4;width++)
    {
        for (height=0;height<4;height++)
        {cout<<list[width][height]<<" ";}
        cout<<endl;
    }
};

但这会打印出来:

R a m o 
Y o l a 
C y n t 
N e n e 

感谢您的帮助。在过去的几个月中,我才刚开始学习C ++,所以我确定我错过了一些数组形式的知识。问题出在我的编程课上,以防您想知道为什么我从更大的数组开始。在此先感谢:)

2 个答案:

答案 0 :(得分:1)

原因是您打印了错误的数组:

for /f %%i in ('systeminfo ^| findstr /B /C:"OS Name" ') do set vard=%%i
echo the operating system name 2 is %vard%

应该是

cout<<list[width][height]

字符串类本身具有cout<<matrix[width][height] ,这就是为什么您没有得到编译器错误而是仅得到指定索引处的字符的原因。

答案 1 :(得分:0)

根据您的代码

string matrix[4][4];

这意味着您尝试声明一个长度为4个字符串的字符串数组,每个字符串的长度为4个字符,这就是为什么要得到此结果的原因。

R a m o  
Y o l a  
C y n t  
N e n e

您可以使用复制数组

std::copy();

或者您也可以使用矢量。

相关问题