返回在函数中创建的 std::list 的第一个节点
return the first node of a std::list created in a function
Interview query:创建一个函数,该函数将从函数内部创建的链表中返回第一个节点;使用 std::list。
std::list<int> function()
{
std::list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
return l.front();
}
这是正确的方法吗?
编辑:问题是返回节点而不是第一个节点的值。
std::list
的公共接口不是根据节点和值定义的。它是为类型 value_type
的元素的容器定义的。因此,您不能访问链表的"节点",只能访问其元素。
如果要从函数的本地std::list
返回第一个元素,则必须返回该元素的副本,因为当函数体超出范围时,所有本地对象都将被销毁。
int func() {
std::list<int> l { 1, 2, 3 };
return l.front(); // Return a copy of the first element.
} // l gets destroyed here.
此访谈查询的目的可能是检查您是否了解本地对象生存期的机制。
例如,您不能从函数内部返回指向本地自动对象的引用或指针:
int& func() { // Notice return type.
std::list<int> l { 1, 2, 3 };
return l.front(); // Return a reference to the first element.
} // l gets destroyed here.
int main() {
const int& number = func(); // Dangling reference!
std::cout << number; // The UB deamons come!
}
如果只需要该值,请将其更改为
int function()
{
...
}
我不知道
"面试查询"是否是一个笑话。以下代码在 Visual Studio 中工作:
struct Node // an assumption !!
{
Node* next_;
Node* prev_;
int data_;
};
Node function()
{
std::list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
Node** p = reinterpret_cast< Node** >( &l.front() );
return *reinterpret_cast< Node* >(p-2);
}
;-)
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 无法使我的第一个Windows OpenGL窗口抬起并运行
- 将参数初始化为构造函数,而不是第一个
- 无法在硬件模式下创建 SGX 安全区 - "invalid launch token"即使文档将无效的启动令牌指定为第一个