Add a new element to a list, and return a reference to that element?

Viewed 67

How can I add a new element to a list, and get a reference to the element that is created in the list?

std::list<My_class> list;
My_class new_obj;
My_class& newly_created_obj_ref = list.add(new_obj); // <-- this won't compile, but it shows what I'm trying to do
3 Answers
My_class& newly_created_obj_ref = *list.insert(list.end(), new_obj);

insert will add an element at the specified position by list.end() and then return an iterator to the inserted element, hence you can dereference this iterator to define your reference

an example

#include <list>
#include <iostream>

int main(){


std::list<int> list {2,3,4};
    int& newly_created_obj_ref = *list.insert(list.end(), 5);
    std::cout << newly_created_obj_ref << "\n";
    for(auto & el : list)
        std::cout << el << " ";

}

The output is

5
2 3 4 5

You can write

My_class& newly_created_obj_ref = ( list.push_back(new_obj), list.back() );

Here is a demonstrative program

#include <iostream>
#include <list>

int main() 
{
    std::list<int> lst;

    int &rx = (lst.push_back( 10 ), lst.back());

    std::cout << rx << '\n';

    rx = 20;

    std::cout << lst.back() << '\n';

    return 0;
}

Its output is

10
20

You are facing two issues here:

  1. To add to a list use the function push_back because add is not a member of list
    myList.push_back(new_obj);
  1. Get the reference to the object just added to the list. The back() function returns a reference to the object at the end of your list, which is now new_obj
    std::list<My_class> myList;
    My_class new_obj;
    myList.push_back(new_obj);
    My_class& newly_created_obj_ref = myList.back();

I've also changed your variable name to myList as there may be confusion between the class std::list and your variable name list

Related