将新元素添加到列表中,并返回对该元素的引用?

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

本文关键字:元素 返回 引用 列表 新元素 添加      更新时间:2023-10-16

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

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.insert(list.end(), new_obj);

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

一个例子

#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

你可以写

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

您在这里面临两个问题:

  1. 要添加到列表,请使用函数push_back因为 add 不是列表的成员
myList.push_back(new_obj);
  1. 获取对刚刚添加到列表中的对象的引用。back()函数返回对列表末尾对象的引用,该对象现在已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,因为类std::list和变量名称之间可能存在混淆list