2014-02-26 18 views
-1

采访查询:创建一个函数,该函数将返回函数内部创建的链表中的第一个节点;使用std :: list。返回在函数中创建的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(); 
} 

这是正确的方法吗?

编辑:问题是返回节点,而不是第一个节点的值。

+2

它,然后应该是'INT函数()'。 – user1810087

+0

这个问题似乎牵扯到两个方向。通常链表中的节点不仅仅是包含的值(它还包括指向下一个节点的指针)。但std :: list将其实际节点类型隐藏为实现细节,只允许您访问所包含的值(在这种情况下,迫使您返回int,正如其他人所建议的那样) –

+1

也许重点是测试您对本地变量(在堆栈上创建,在函数退出时销毁)与分配(在堆上使用'new'创建,在函数退出后仍然存在)。返回一个迭代器到一个局部变量将是一个坏主意,因为它不会存在迭代器被取消引用 –

回答

0

如果你只需要值,将其更改为

int function() 
{ 
    ... 
} 
1

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! 
} 
0

我不知道“采访查询”是否是一个笑话。下面的代码在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); 
} 

;-)

相关问题