向列表中添加一个新元素,然后 return 对该元素的引用?

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

如何向列表中添加新元素,并获取对在列表中创建的元素的引用?

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

你可以写

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

这是一个演示程序

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

它的输出是

10
20
My_class& newly_created_obj_ref = *list.insert(list.end(), new_obj);

insert 将通过 list.end() 在指定位置添加一个元素,然后 return 一个迭代器到插入的元素,因此你可以取消引用这个迭代器来定义你的引用

一个例子

#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 << " ";

}

输出为

5
2 3 4 5

您在这里面临两个问题:

  1. 要添加到列表,请使用函数 push_back,因为添加不是列表的成员
    myList.push_back(new_obj);
  1. 获取对刚刚添加到列表中的对象的引用。 back() 函数 returns 对列表末尾对象的引用,现在是 new_obj
    std::list<My_class> myList;
    My_class new_obj;
    myList.push_back(new_obj);
    My_class& newly_created_obj_ref = myList.back();

我还将您的变量名称更改为 myList,因为 class std::list 和您的变量名称 list 之间可能存在混淆