Home > Back-end >  Returning a reference to object from vector
Returning a reference to object from vector

Time:01-05

I am a complete C beginner so all of the concepts are quite new to me. The problem at hand is that I have a vector which consists of objects such as

vector<Item> inventory { item1, item2, item3 };

I pass it to a function by reference and then need to pass it to another function to retrieve an object which has the itemId I need

Item& returnItem(vector<Item> &vec, int id) {
    for(Item &i : vec) {
        if(i.getItemId() == id) {
            return i;
        }
    }
}

void f(vector<Item> &vec, int id) {
    Item foundItem = returnItem(vec, id);
}

I have another function that I would need to pass this object to but obviously it's not working as intended as using foundItem.setItemId() after running the returnItem function doesn't change anything inside the vector.

Is there any easy way to fix this or what would be a better way to do this?

CodePudding user response:

Without a complete Minimal, Reproducible Example, it's hard to know for sure what is the problem.

However - my guess is that the cause is this line:

Item foundItem = returnItem(vec, id);

returnItem returns a reference, but the assignment to foundItem actually create a copy (because foundItem is of type Item, not reference to Item).

To fix it change it to:

//---V---------------------------------
Item & foundItem = returnItem(vec, id);

Now foundItem will be a reference to the item in the vector, and modifying it will change the item in the vector.

Another issue you have to consider is the case where the item is not found in the vector. As @Eljay commented, one of the options is to throw an exception. Another is to return a reference to static instance that represent an invalid value.

  • Related