在链表C ++中搜索Object的某个字段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在链表C ++中搜索Object的某个字段相关的知识,希望对你有一定的参考价值。

int Search(int x) {
        Node* temp = head;
        int pos = 1;
        while(temp != nullptr){
            if(temp->data == x)
                return pos;
            else{
                temp=temp->next;
                pos++;
            }
        }
        return 0;
}

此搜索功能用于搜索我创建的链表中的整数,并返回整数的位置。我现在使用的链接列表涉及具有四个字段的Person对象:名称,年龄,身高和体重。如何编写搜索功能以按名称搜索用户,然后在找到后打印出整个人员?我试着写这个,但它不起作用:

Person Search(Person*A) {
        Node* temp = head;
        int pos = 1;
        while(temp != nullptr){
            if(temp->data == A)
                return *A;
            else{
                temp=temp->next;
                pos++;
            }
        }
        return *A;
}

最后我想我需要名字的setter / getters,我需要传递参数搜索(Person.getName()),但这也是一个错误。有人可以向我解释如何做到这一点?我没有在网上找到任何类似的东西,所以任何帮助将不胜感激。提前致谢!

答案

我认为搜索功能类似于以下代码:

Person* Search(std::string search_name) {
        Node* temp = head;
        while(temp != nullptr){
            if(temp->data->name == search_name){ //compare name
                return temp->data;
            }
            temp=temp->next;
        }
        return nullptr;
}

输入要搜索的名称,该函数将返回人物指针

以上是关于在链表C ++中搜索Object的某个字段的主要内容,如果未能解决你的问题,请参考以下文章