将新元素添加到列表中,并返回对该元素的引用?
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.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
您在这里面临两个问题:
- 要添加到列表,请使用函数
push_back
因为 add 不是列表的成员
myList.push_back(new_obj);
- 获取对刚刚添加到列表中的对象的引用。
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
相关文章:
- lower_bound()返回最后一个元素
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 反转后不返回最后一个元素
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 第 i 个元素返回 i 的函数数组
- 将新元素添加到列表中,并返回对该元素的引用?
- C++ 将向量中出现 n 次的所有元素作为向量返回
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 返回向量元素的 l 值的正确方法是什么?
- C++函数返回两个 char 数组的相同索引元素
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 函数返回包含输入容器的特定元素的容器
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- 返回纯虚拟基类的向量的元素
- 比较 C++ 中的两个数组,并根据元素的匹配或不匹配返回值
- 在位置 i 处插入元素,并根据 i 第一个元素返回信息