【问题标题】:Insert function using templates loses number使用模板插入功能丢失编号
【发布时间】:2014-02-27 03:49:34
【问题描述】:

大家好,我只是有一个小问题。当我在我的有序列表中插入数字时,除了我插入的最后一个数字之外,每个数字都会出现。我拥有的计数变量表明,目前,所有 6 个都在其中。但是当我打印列表时,最后一个丢失了。任何帮助都将不胜感激。时间至关重要,因为它在晚上 11:00 到期

为有序列表插入函数:

template <class T>
void OListType<T>::insert (const T& item) {
 NodeType<T> *curr=this->head, *prev=NULL;
 while (curr!=NULL && curr->item<item) {
     prev = curr;
     curr = curr->next;
 }
 if (prev==NULL) {
     this->head = new NodeType<T>;
     this->head->item=item;
     this->head->next=curr;
  }
 else{
     prev->next=new NodeType<T>;
     prev->next->item=item;
     prev->next->next=curr;
 }
 ++this->count;
}

主程序:

#include <iostream>
#include "ListType.h"
#include "UListType.h"
#include "OListType.h"

using namespace std;

int main() {
 OListType<int> OList_int;
 UListType<int> UList_int;

 OList_int.insert(45);
 OList_int.insert(100);
 OList_int.insert(7);
 OList_int.insert(83);
 OList_int.insert(29);
 OList_int.insert(49);

 cout<< "The Ordered List size after inserts: ";
 cout<< OList_int.size() << endl << endl;

 cout << "The Ordered List values after inserts: ";
 cout << OList_int << endl << endl;

return 0;
}

Ostream 重载代码:

template <class U>
std::ostream &operator<< (std::ostream &out, const ListType<U> &list) {
 if (!list.empty()) {
   NodeType<U> *temp=list.head->next;
   out << list.head->item;
   temp=temp->next;
   while(temp!=NULL) {
     out << "," << temp->item;
     temp=temp->next;
   }
 }
 return out;
}

如果您需要更多代码,我会提供。

【问题讨论】:

  • 您的 insert() 看起来不错。你能添加你的“operator
  • 好的,我添加了。告诉我你的想法

标签: c++ class templates operator-overloading


【解决方案1】:
template <class U>
std::ostream &operator<< (std::ostream &out, const ListType<U> &list) {
if (list.head) {
 NodeType<U> *temp=list.head;
 out << list.head->item;
 temp=temp->next;
 while(temp!=NULL) {
 out << "," << temp->item;
 temp=temp->next;
 }
}
return out;
}

进行了以下更改 NodeType *temp=list.head; :)

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2014-09-10
    • 2015-07-14
    • 1970-01-01
    • 2012-12-25
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多