2013-02-11 2 views
0

Я действительно новичок в C++, и у меня возникают проблемы с работой функции insert() с LinkedList. Вот код, который я получил, начиная от:C++ No Default Constructor? Пытаться создать метод вставки для LinkedList

#include <iostream> 
#include <cassert> 
#include <stdexcept> 
using namespace std; 

template<typename T> class mylist; 

template<typename T> 
ostream& operator<< (ostream &out, const mylist<T> &l); 

template <typename T> 
class mylist { 
public: 
    // node definition 
    struct node { 
     T data; 
     node* next_ptr; 
     // node constructor 
     node(const T &d, node* n):data(d),next_ptr(n){} 
    }; 

    // alternative node definition 
    /* 
    class node { 
    public: 
     T data; 
     node* next_ptr; 
     // node constructor 
     node(const T&d, node* n):data(d),next_ptr(n){} 
    }; 
    */ 

    // linked list head pointer 
    node* head_ptr; 

    //friend ostream& operator<< <>(ostream& out, const mylist<T>&l); 
    friend ostream& operator<< (ostream &out, const mylist<T> &l); 

public: 
    // default constructor 
    mylist():head_ptr(nullptr) {} // head_ptr points nowhere 

    // adds element to the front of the linked list 
    void push_front(const T &elem) { 
     head_ptr = new node(elem, head_ptr); 
    } 

    // check if linked list is empty 
    bool empty() { return head_ptr == nullptr;} 

    // number of nodes in linked list 
    unsigned size() { return length();} 
    unsigned length() { 
     unsigned l = 0; 
     for(node* current = head_ptr; current != nullptr; current = current->next_ptr) { 
      ++l; 
     } 
     return l; 
    } 

    // copy constructor 
    mylist(const mylist &other) 
    { 
     for(node* current_other = other.head_ptr; 
      current_other != nullptr; 
      current_other = current_other->next_ptr) { 
       this.push_back(current_other->data); // inefficient, but easy :) 
     } 
    } 

    // destructor 
    ~mylist() { 
     node* tmp; 
     for(node* current = head_ptr; 
       current != nullptr; 
       current = tmp) { 
      tmp=current->next_ptr; 
      delete current; 
     } 
    } 

    // at accessor method (returns the element at the ith position in the linked list) 
    T& at(unsigned i){ 
     unsigned l=0; 
     node* current; 
     for(current = head_ptr; current != nullptr; current = current->next_ptr) { 
      if(l == i) 
       break; 
      ++l; 
     } 
     if (current == nullptr) 
      throw out_of_range("index i is out of range"); 
     else 
      return current->data; 
    } 

    // bracket operator (returns the element at the ith position in the linked list) 
    T& operator[](unsigned i){ 
     return at(i); 
    } 

    // adds element to the end of the linked list 
    void push_back(const T &elem) { 
     if(empty()) { 
      push_front(elem); 
      return; 
     } 
     node* last_ptr; 
     for(last_ptr = head_ptr; last_ptr->next_ptr != nullptr; 
      last_ptr = last_ptr->next_ptr); 

     last_ptr->next_ptr = new node(elem, nullptr); 

    } 

    // prints the contents of the linked list 
    void print_all(void) { 
     cout << "mylist{"; 
     for(node* current_ptr = head_ptr; 
       current_ptr != nullptr; 
       current_ptr = current_ptr->next_ptr){ 
      cout << current_ptr->data << " "; 
     } 
     cout << "}" << endl; 
    } 

Я пытаюсь создать новую функцию, вставить (константный T & эля, без знака I). Это назначение описано в комментарии следующего кода:

// inserts the element at position i in linked list. 
    // throws out of range error if position i not in list. 
    void insert (const T &elem, unsigned i) { 
     unsigned l=0; 
     node* current, prev; 
     for(current = head_ptr; current != nullptr; current = current->next_ptr) { 

      if(l == i) 
       break; 
      ++l; 
      prev = current; 
     } 
     if (current == nullptr) 
      throw out_of_range("index i is out of range"); 
     else 
     { 
      prev->next_ptr = new Node (elem, current); 
     } 
    } 

Моя проблема заключается в том, что я получаю следующее сообщение об ошибке, и я понятия не имею, как это исправить, или что это значит:

1>c:\users\jaysen\documents\data structures\lab 2\lab 2\mylist_tpt.h(184): error C2512: 'mylist<T>::node' : no appropriate default constructor available 
1>   with 
1>   [ 
1>    T=std::string 
1>   ] 
1>   c:\users\jaysen\documents\data structures\lab 2\lab 2\mylist_tpt.h(182) : while compiling class template member function 'void mylist<T>::insert(const T &,unsigned int)' 
1>   with 
1>   [ 
1>    T=std::string 
1>   ] 
1>   c:\users\jaysen\documents\data structures\lab 2\lab 2\mylist_main.cpp(20) : see reference to class template instantiation 'mylist<T>' being compiled 
1>   with 
1>   [ 
1>    T=std::string 
1>   ] 

Заранее спасибо за любую помощь, которую вы можете мне дать!

+1

Сообщение об ошибке так же ясно, как и оно. –

ответ

0

Ошибки в этой строке:

node* current, prev; 

Объявляет current быть указателя на node и prev быть экземпляр node. Деклараторы, такие как *, & или [], применяются только к одному идентификатору каждый раз. Поэтому лучше разместить их рядом с идентификатором, а не с типом:

node *current, *prev; 
+0

Спасибо вам большое! Я не понимал, что означал звездочка, мой учитель никогда не объяснял это. Это имеет больше смысла, и теперь моя программа работает отлично! Не могли бы вы объяснить мне, что означают два других декларатора? –

+0

@JaysenStoudt '&' объявляет ссылку, '[]' (обычно с числом между ними) объявляет массив. Если ваш учитель не покрывает их, стыдно за него, и вы могли бы изучить их из книги [C++] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and -список). – Angew

0
node* current, prev; 

Должно быть:

node *current, *prev; 

Как вы написали, prev не указатель. Это был node.

И, как указано в заявлении, нет способа построить node таким образом. (Это требует два параметра)

Смежные вопросы