【发布时间】:2016-08-08 19:50:14
【问题描述】:
我已经找到了关于从链表中插入和删除对象的问答。但我的问题是从链接列表访问和更新这些对象。
以下代码是学校项目的一部分,我需要在其中制作工资单对象的链接列表。我需要能够插入、删除、按特定参数搜索以及更新员工工资单信息。我在插入和删除时没有问题。但是我对如何搜索和访问这些对象以与它们的变量进行交互有点迷茫。
在 InList 函数中,我传递了一个链表和一个 int,创建 Payroll 对象并将该 int 分配为员工编号变量。然后我使用 P 的搜索函数并将该工资单对象作为参数传递。
void InList(const orderedLinkedList<Payroll>& P, int employee_number)
{
Payroll payListEmpNum;
payListEmpNum.setEmployeeNumber(employee_number);
if (P.search(payListEmpNum) == 1)
{
payListEmpNum.printPayroll();//this is just printing my local employee_number.
}
else
{
cout << "Sorry, that employee was not found.\n" << endl;
};
}
这是我的有序链接列表类的搜索功能。它遍历列表,并根据我发送的对象测试每个对象的员工编号。我可以将当前指针发送到我的 Payroll 类以打印记录,但这并不能让我访问数据。
template <class Type>
bool orderedLinkedList<Type>::search(const Type& searchItem) const
{
bool found = false;
nodeType<Type> *current; //pointer to traverse the list
current = first; //start the search at the first node
while (current != NULL && !found)
if (current->info >= searchItem)
found = true;
else
current = current->link;
if (found) {
found = (current->info == searchItem); //test for equality
}
return found;
}//end search
但是,由于搜索函数不返回任何数据,InList 只打印我的局部变量,employee_number,并且为所有其他变量打印 null。
我不确定如何访问我的对象的变量。我应该写一个不同的函数来处理这个吗?这是指针问题吗?
谢谢!
【问题讨论】:
-
在设计链表时应该注意这一疏忽。如果用户无法获取存储在其中的信息,那么链表(或任何其他数据结构)有什么用?对字符串类进行成像,您无法从中取出字符串。是否有意义?所以你应该做的可能就是做STL做的事情,那就是返回一个指向找到的数据的指针,如果没有找到,则为NULL。
-
我同意一个名为
search的成员函数不应该返回布尔值,而是返回指向找到的第一个元素的指针(如果找到的话),以及指向 null 的指针(如果没有找到的话)。 -
template <class T> const T *find( const orderedLinkedList<T>& list, std::function<bool(const T&)> predicate )看起来不错。如果您的列表按某个键排序,则无需重新排序就无法修改该键。对于其他条目,您当然可以更改。那么上述函数的非常量版本就可以工作了。 -
嗯,这个链表类是由我用于该类的书提供的。所以,不是我写的,而是必须要用的。
标签: c++ pointers object linked-list