链表数组给C++带来麻烦

Array of Linked Lists Trouble C++

本文关键字:麻烦 C++ 数组 链表      更新时间:2023-10-16

首先,我对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();

似乎就是这样。每次循环时,你都会给下一个向量添加一个值。