c++ - 你如何使用这个数组而不是请求输入?

标签 c++ arrays

<分区>

在类里面学习数组。尝试通过使用我的数组而不是下面的示例来玩下面的代码来理解它们。

数组示例:

string[16] = {"Toelle","Red Lightning","Penguins","Tigers","You Know It","VP4LIFE","OG      WOW","Indy","Ok","NOSER","LAK State","THE State","NY","Ks","Tahaa","Fosda"};

代码:

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

// This program inputs a list of team names and runs a random tournament to find the winner.

void print_teams(string *ptr, int size)
{
    for(int team = 0; team < size; team++)
    {
        cout << "Team "<<team<<"="<<ptr[team]<<endl;
    }
}
int main()
{
    const int NTEAMS=4;
    string *teams = new string[NTEAMS];

    // Get input from the user for the teams
    for(int team = 0; team < NTEAMS; team++)
    {
        cout <<"Enter the name for team #"<<team<<":";
        getline(cin, teams[team]);
    }
    print_teams(teams, NTEAMS);

    int teams_left = NTEAMS;
    string *team_ptr = teams;

    for(int round = 0; teams_left > 1; round++) {
        // Allocate space for the winners
        int new_size = teams_left/2;
        string *new_teams = new string[new_size];
        // Run a round of the tournament
        for(int team = 0; team < teams_left; team+=2) 
        {
            // Pick a winner
            int winner = rand()%2;
            //update the winners array
            new_teams[team/2] = team_ptr[team+winner];
        }
        cout << "Round "<<round<<endl;
        print_teams(new_teams, new_size);
        // Update the size and team pointer for the next round
        teams_left = new_size;
        // Free up the space for the old teams list
        delete[] team_ptr;
        team_ptr = new_teams;
    }
    system("pause");

}

最佳答案

您需要将处理数组的代码移动到一个单独的函数中,该函数接收数组作为参数。该数组可以从 cin、硬编码或任何其他来源读取。这样您就可以在这两种情况下重用您的代码。这里的关键概念是将输入与实际计算解耦。

关于c++ - 你如何使用这个数组而不是请求输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13069858/

相关文章:

c++ - 在 firebreath 插件上创建子可编辑文本框窗口

c++ - 非类型模板参数的隐式转换如何工作?

javascript - 为什么我的数组中的项目不显示在单独的行中?

python - 如何获取一个数组中包含在另一个数组中的值的所有索引?

java - 使用其他东西代替字符串

arrays - 如何使用 NSKeyedArchiver swift 将复杂的 Arrayobjects 保存到设备

c++ - Clion 代码生成变灰

c++ - 底片全黑

c++ - 如何使用 Boost.serialize 序列化派生模板类?

javascript - jQuery:将数组项与文本匹配>从数组中删除项