链表数组给C++带来麻烦
Array of Linked Lists Trouble C++
首先,我对C++非常陌生,主要使用过Java、JavaScript、C#和Scala等语言。
我正在尝试编写一个程序,该程序将从控制台中获取一个数字,该数字将确定团队的数量(以链表的形式(例如,numTeams=5;表示5个链表)),然后将接受以下输入,以便第一个值将被添加到第一个链表,然后第二个值将添加到第二个链表,依此类推,直到所有i值都被分配给所有n个团队。此外,当所有链接列表都填充了相等数量的值时,它将从第一个链接列表重新开始,并再次遍历它们,将值添加到每个列表中。
我知道我必须制作一系列链表,但我不确定如何以我所说的方式进一步分配值。
任何帮助都将不胜感激!
以下是我目前所拥有的:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
class balanceTeams{
// Struct inside the class LinkedList
struct Node {
int x;
Node *next;
};
public:
// constructor
balanceTeams(){
head = NULL; // set head to NULL
}
// New value at the beginning of the list
void addUnit(int val){
Node *n = new Node(); // create new Node
n->x = val; // set value
n->next = head; // make the node point to the next node.
// If the list is empty, this is NULL
head = n; // head point at the new node.
}
// returns the first element in the list and deletes the Node.
int popUnit(){
Node *n = head;
int ret = n->x;
head = head->next;
delete n;
return ret;
}
//void swapUnit()
//void moveUnit()
private:
Node *head; // pointer to the first Node
};
int main() {
string line;
int numTeams = 0;
int lines = 0;
vector<balanceTeams> vect;
//int team_size = lines / numTeams;
getline(cin, line);
numTeams = atoi (line.c_str());
vect.resize(numTeams);
cout << "Num teams: " << numTeams << endl;
while (getline(cin, line)) {
cout << "Unit " << line << endl;
}
return 0;
}
编辑:三个错误:
balanceTeams.cpp: In function ‘int main()’:
balanceTeams.cpp:72:23: error: no matching function for call to
‘balanceTeams::addUnit(std::string&)’
vect[i].addUnit(line);
^
balanceTeams.cpp:72:23: note: candidate is:
balanceTeams.cpp:25:7: note: void balanceTeams::addUnit(int)
void addUnit(int val){
^
balanceTeams.cpp:25:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘int’
您的代码中似乎缺少的只有:
1) 一些错误检查。进入的团队数量必须至少为一个。如果有人输入0或负值,则显示一条错误消息,然后退出。
2) 初始化
size_t i=0;
在现有循环之前。
3) 在循环中,解析现有值,然后调用
vect[i].addUnit(new_value);
4) 在循环结束时为下一个迭代器增加索引
i=(i+1) % vect.size();
似乎就是这样。每次循环时,你都会给下一个向量添加一个值。
相关文章:
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 查找奇数平方和时遇到麻烦
- 将双倍转换为 LPARAM 的麻烦
- 麻烦得到提升::记录器编译
- 翻转 ppm 图像C++麻烦
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 搬家turtlebot_gazebo麻烦
- CSUF EPP - 你有什么想法(在添加到链接列表末尾时遇到麻烦)
- 我的期末考试遇到了麻烦.代码不断循环回到我的订购菜单,不会显示我的总价
- 作为一个C++新手,我遇到了麻烦
- 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- 找麻木的麻烦
- MySQL 从注入过渡到参数化时遇到麻烦
- 字符串和双精度的麻烦,等值后再得到一个数字
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 自定义QVariant麻烦
- 串和阵列的麻烦
- 在C 向量中修改对象值的麻烦
- C DirectX 11从第二个顶点缓冲区呈现麻烦
- 编译 opencv 示例麻烦