c++ - 在 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 G
is bool G[x][y]
,我用它来创建元素与其包之间的关系,但这不起作用,因为它没有给我输入的顺序。
我考虑过创建一个链接列表,但我不知道如何N
使用键盘给出的创建列表N
,然后访问每个列表。
我不知道是否清楚,但我不需要随机访问每个包的每个元素,我只需要一个包,按照输入的顺序迭代它的元素。
解决方案
这是适合的情况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;
}
推荐阅读
- java - 当我在 Xamarin 中构建解决方案时,我看到错误:“javac.exe”以代码 3 退出
- c - 如何在c中控制二维字符数组?
- html - 在给定任意颜色范围的情况下均匀分布画布渐变颜色
- vuejs2 - 有没有办法仅在开发期间将数据加载到商店中?
- python - 如何有效地在一个上限宽度水平写入 6 行卦?
- python - 如何在 tkinter 中禁用绑定到自己框架的其他两个单选按钮
- javascript - 我怎样才能访问从这个承诺返回的数据?
- html - 使用 Laravel 为 foreach 循环中的每个复选框创建一个表单
- php - 一种获取单个数组的简单方法,该数组包含 PHP 中嵌套对象中包含的所有整数
- bash - Git 在 npm 脚本中使用动态分支名称向上游推送