所以我正在做一个项目,我不知道我的问题是什么。我是使用和学习指针的新手,所以这可能是我没有看到的,但当我运行print方法时,它会显示列表中的每一项,其值与上一项相同。我不明白为什么它不仅添加到列表中,而且覆盖以前的条目。(我还没有完成其余的功能,所以我没有包括它们,main下的所有内容都是作为模板提供的。目前我只是想克服这个障碍,因为我似乎在网上找不到答案。(
#include <algorithm>
#include <iostream>
#include <time.h>
#include "CSVparser.hpp"
using namespace std;
double strToDouble(string str, char ch);
struct Bid {
string bidId; // unique identifier
string title;
string fund;
double amount;
Bid() {
amount = 0.0;
}
Bid* nextNode = 0;
};
class LinkedList {
private:
Bid* head;
Bid* tail;
int size;
public:
LinkedList();
virtual ~LinkedList();
void Append(Bid* bid);
void PrintList();
};
LinkedList::LinkedList() {
this->head = 0;
this->tail = 0;
this->size = 0;
return;
}
LinkedList::~LinkedList() {
}
void LinkedList::Append(Bid* bid) {
if (this->head == 0)
{
this->head = bid;
this->tail = bid;
}
else
{
this->tail->nextNode = bid;
this->tail = bid;
}
size += 1;
return;
}
void LinkedList::PrintList() {
Bid* currBid = this->head;
for (int i = 0; i < size; i++)
{
cout << currBid->bidId << ": " << currBid->title << " | " << currBid->amount << " | " << currBid->fund << endl;
currBid = currBid->nextNode;
}
return;
}
int main(int argc, char* argv[]) {
string csvPath, bidKey;
switch (argc) {
case 2:
csvPath = argv[1];
bidKey = "98109";
break;
case 3:
csvPath = argv[1];
bidKey = argv[2];
break;
default:
csvPath = "eBid_Monthly_Sales_Dec_2016.csv";
bidKey = "98109";
}
clock_t ticks;
LinkedList bidList;
Bid bid;
int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << " 1. Enter a Bid" << endl;
cout << " 2. Load Bids" << endl;
cout << " 3. Display All Bids" << endl;
cout << " 4. Find Bid" << endl;
cout << " 5. Remove Bid" << endl;
cout << " 9. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
bid = getBid();
bidList.Append(&bid);
displayBid(bid);
break;
case 2:
ticks = clock();
loadBids(csvPath, &bidList);
cout << bidList.Size() << " bids read" << endl;
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
cout << "time: " << ticks << " milliseconds" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 3:
bidList.PrintList();
break;
case 4:
ticks = clock();
bid = bidList.Search(bidKey);
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
if (!bid.bidId.empty()) {
displayBid(bid);
} else {
cout << "Bid Id " << bidKey << " not found." << endl;
}
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 5:
bidList.Remove(bidKey);
break;
}
}
cout << "Good bye." << endl;
return 0;
}
样本输出
main
函数中只有一个名为bid
的Bid
对象。每次将&bid
传递给Append
函数时,都会传递同一对象的地址。所以你的链表包含了一堆指针,它们都指向同一个内存。
解决这个问题的一种方法是在Append
中分配新内存,如下所示:
void LinkedList::Append(Bid* bid_arg) {
Bid *bid = new Bid{*bid_arg}; // allocate memory with the value
// pointed at by the pointer that is passed in
// append bid to the linked list
}