首页 > 解决方案 > 在 C++ 中从键盘创建 N 个链表,即 N 个数字

问题描述

我的程序有问题。我会尽力解释,以便你能帮助我。

想象一下,您想要有N袋子,并且对于每个袋子,您想输入一些球(每个袋子的最大球数 = 10)。

我有一个函数,它首先引入N袋子的数量,然后它从用户那里为每个袋子读取一行输入,例如1 3 4 9,指示输入到该袋子中的元素,等等每个袋子,直到袋子N

我遇到的问题是,我怎样才能“记住”所有球的输入顺序?在上面的示例行中,顺序是先 1,然后是 3,然后是 4,最后是 9。

在其他功能中,我需要每个 bag i,按照输入的顺序获取它的元素,并用它们做一些事情。

我的代码类似于

for (int i = 0; i < N ; i ++){
    //read all numbers
    //and for each number "j"
    G[i][j] = true;
}

Where Gis bool G[x][y],我用它来创建元素与其包之间的关系,但这不起作用,因为它没有给我输入的顺序。

我考虑过创建一个链接列表,但我不知道如何N使用键盘给出的创建列表N,然后访问每个列表。

我不知道是否清楚,但我不需要随机访问每个包的每个元素,我只需要一个包,按照输入的顺序迭代它的元素。

标签: c++linked-list

解决方案


这是适合的情况std::vector。您不需要使用链表(如std::list)。

例如:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <limits>

struct Bag
{
    int NumBalls;
    int Balls[10];

    Bag() : NumBalls(0) {}
};

int main()
{
    int N;
    std::cout << "How many bags do you want? ";

    if (!((std::cin >> N) && (N > 0)))
    {
        std::cout << "Bad input!" << std::endl;
        return 0;
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::vector<Bag> Bags(N);

    for (int i = 0; i < N; ++i)
    {
        std::cout << "Enter balls for bag " << i+1 << ": ";

        std::string line;
        if (!std::getline(std::cin, line))
            break;

        std::istringstream iss(line);

        Bag &bag = Bags[i];
        int ball;

        do
        {
            if (!(iss >> ball))
            {
                if (!iss.eof())
                    std::cout << "Bad input!" << std::endl;
                break;
            }

            bag.Balls[bag.NumBalls] = ball;
            bag.NumBalls++;
        }
        while (bag.NumBalls < 10);
    }

    std::cout << std::endl;

    for (int i = 0; i < N; ++i)
    {
        std::cout << "Bag " << i+1 << " contains:";

        Bag &bag = Bags[i];
        for(int j = 0; j < bag.NumBalls; ++j)
            std::cout << " " << bag.Balls[j];

        std::cout << "\n";
    }

    return 0;
}

现场演示


推荐阅读