通过变量循环

时间:2019-02-20 06:12:19

标签: c++ algorithm loops c++11 ref

到目前为止,我已经使该代码正常工作,但是现在,它仅在多维数组中循环时才存储最后一个变量。

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

int main() 
{
    const int columns = 5, rows = 5;
    int menuSelection;
    string word1 = "sloan", word2 = "horse", word3 = "eqrit", word4 = "house", word5 = "water";
    string table[rows][columns];

    for (auto &var : { ref(word1), ref(word2), ref(word3), ref(word4), ref(word5) })
    {
        for (int i = 0; i < rows; ++i) 
        {
            for (int j = 0; j < columns; ++j) 
            {
                string test = var;
                table[i][j] = test[i];
            }
        }
    }

    for (int i = 0; i < columns; ++i)
    {
        for (int j = 0; j < rows; ++j)
        {
            std::cout << table[i][j] << ' ';
        }
        std::cout << std::endl;
    }
}

输出为:

w w w w w 
a a a a a 
t t t t t 
e e e e e 
r r r r r 

我希望它在数组输出的每一行上显示不同的单词:

s l o a n
h o r s e 
e g r i t    
h o u s e    
w a t e r

3 个答案:

答案 0 :(得分:2)

如果您只关心期望的输出,那么您要做的就是很多不必要的代码。当然,要学习一些东西,您可以采用其他更长的方法来获得结果。

但是,如果您关心一个简单的解决方案,则只需要std::arraystd::string中的一个,并遍历它们即可打印。

#include <iostream>
#include <array>
#include <string>

int main() 
{
    const std::array<std::string, 5> words { "sloan", "horse", "eqrit", "house", "water" };

    for (const auto& word: words)
    {
        for (const char charactor: word)  std::cout << charactor << " ";
        std::cout << '\n';
    }
    return 0;
}

答案 1 :(得分:1)

您的代码将循环字符串列表,并像这样在每个空格处设置每个字符

循环1

s s s s s
l l l l l
o o o o o
a a a a a
n n n n n

循环2

h h h h h
o o o o o
r r r r r
s s s s s
e e e e e

循环3 ...

依此类推

改为尝试此代码

const int columns = 5, rows = 5;

string list[] = {"sloan", "hores", "eqrit", "house", "water"};
string table[rows][columns];

for(int i = 0; i < rows; ++i)
{
    string currentString = list[i];

    for(int j = 0; j < columns; ++j)
    {

        table[i][j] = currentString[j];
    }
}

for(int i = 0; i < columns; ++i)
{
    for(int j = 0; j < rows; ++j)
    {
        std::cout << table[i][j] << ' ';
    }
    std::cout << std::endl;
}

答案 2 :(得分:1)

您正在遍历每个单词,用第一个单词中的单个字符填充整个数组,然后用第二个单词中的字符,然后是第三个单词的字符覆盖整个数组,依此类推。

所以是的,最后,数组只填充了最后一个单词的字符。

您需要重新考虑循环。当2个就足够时,您不需要3个嵌套循环。

尝试更多类似的方法:

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

int main() {
    const int columns = 5, rows = 5;

    string words[] = {
        "sloan",
        "horse",
        "eqrit",
        "house",
        "water"
    };

    string table[rows][columns];
    for (int i = 0; i < rows; ++i) {
        string &test = words[i];
        for (int j = 0; j < columns; ++j) {
            table[i][j] = test[j];
        }
    }

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            std::cout << table[i][j] << ' ';
        }
        std::cout << std::endl;
    }

    return 0;
}

输出

s l o a n 
h o r s e 
e q r i t 
h o u s e 
w a t e r 

Live Demo