2015-03-18 39 views
0

首先,我對C++非常陌生,主要使用Java,JavaScript,C#和Scala等語言。鏈接列表陣列Trouble C++

我想寫一個程序,將從控制檯採取一個數字,這將確定團隊的數量(以鏈接列表的形式(例如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’ 
+2

如果你是新的C可能是有益++ [讀一本書第一(http://stackoverflow.com/a/388282/332733)C++是有點複雜 – Mgetz 2015-03-18 23:28:37

+0

您正在試圖解決兩個問題在一次:將值分配給數組中的元素,並將值添加到鏈接列表。你需要哪一個幫助? – Beta 2015-03-18 23:33:10

+0

可能將值分配給數組中的元素更多 – Jaromando 2015-03-18 23:36:44

回答

0

所有這一切似乎是從代碼中缺少的是:

1)某些錯誤檢查。進入隊伍的數量必須至少有一個。如果有人輸入0或負值,則顯示錯誤消息並進行保護。現有的循環之前

2)初始化

size_t i=0; 

3)在循環中,解析現有的值,然後調用

vect[i].addUnit(new_value); 

4)增量的索引處的循環結束時,對下一個迭代

i=(i+1) % vect.size(); 

這似乎是吧。每次循環時,都會爲下一個向量添加一個值。

+0

嘗試實施時出現三個錯誤。我將在我原來的文章中加入,以便您更好地看到它。 – Jaromando 2015-03-19 02:39:49

+0

編譯錯誤不言自明。當你將一個std :: string作爲參數傳遞時,你將你的類方法聲明爲一個參數的int。您需要下定決心,無論您的鏈接列表是存儲整數還是std :: strings,然後相應地更改代碼。這正是編譯器錯誤所說的。錯誤文本的哪部分你不明白? – 2015-03-19 23:45:30