返回在函数中创建的 std::list 的第一个节点

return the first node of a std::list created in a function

本文关键字:list 第一个 节点 std 创建 返回 函数      更新时间:2023-10-16

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

;-)