Fall0ut
Fall0ut

Reputation: 71

Searching for a certain field of an Object in a linked list C++

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;
}

This search function is used in order to search for an integer within a linked list that I have created and return the location of the integer. I am now working with a Linked List that involves Person objects with four fields: name, age, height, and weight. How would I go about writing a Search function to search for a user by their name and then printing out the whole Person once found? I tried writing this, but it would not work:

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;
}

Finally I figured that I needed setters/getters for name and I would need to pass the Parameter Search(Person.getName()), but this was throwing an error as well. Can someone explain to me how to do this? I have not found anything similar to this online so any help would be greatly appreciated. Thanks in advance!

Upvotes: 0

Views: 325

Answers (1)

Gleipnir
Gleipnir

Reputation: 36

i think that the search function is like the following code:

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;
}

Input the name you want to search,the function will return the person pointer

Upvotes: 1

Related Questions