gpt4 book ai didi

c++ - 如何访问 std::list 的第一个元素?

转载 作者:可可西里 更新时间:2023-11-01 16:36:26 25 4
gpt4 key购买 nike

我有一个列表 std::list<T *> *l; .此列表不为空且具有一些值。我的问题是如何正确访问项目?我不需要遍历列表。我只想要第一个项目。

std::list<T*>::iterator it = l->begin();

if (it != l->end())
{
// accessing T
int value = (*it)->value(); // Is this safe?
}

或者我还应该检查 null 吗?

if (it != l->end() && (*it))
{
// accessing T
int value = (*it)->value();
}

最佳答案

如果你被迫使用std::list<T*> myList;假设T定义为:

struct T
{
T(const char* cstr) : str(cstr){ }
std::string str;
};

然后只需使用 std::list::front 访问第一个元素:

std::string firstStr = myList.front()->str;

请注意,在本例中为 myList.front()返回对列表中第一个元素的引用,在本例中是对指针的引用。因此,您可以将其视为指向第一个元素的指针。

关于您关于 NULL 的问题:当您使用指针容器时,一旦对象被破坏,指针就应该从容器中移除。一旦你开始使用指针,这通常意味着你是负责与这些指针指向的对象相关的内存管理的人(这是你应该尽可能喜欢 std::list<T> 而不是 std::list<T*> 的主要原因) .

NULL还差指针是悬挂指针:当你创建一个对象时,将它的地址存储在你的容器中,但是一旦对象被销毁你就不会从你的容器中删除这个地址,那么这个指针将变得无效,并且尝试访问该指针指向的内存将产生未定义的行为。所以不仅你应该确保你的 std::list不包含 NULL指针,您还应该确保它只包含指向仍然存在的有效对象的指针。

因此当您清理这些元素时,您会发现自己从列表中删除指针并立即删除它们指向的对象:

std::list<T*> myList;

myList.push_back(new T("one"));
myList.push_back(new T("two"));
myList.push_back(new T("three"));
myList.push_back(new T("four"));

while (!myList.empty())
{
T* pT = myList.front(); // retrieve the first element
myList.erase(myList.begin()); // remove it from my list
std::cout << pT->str.c_str() << std::endl; // print its member
delete pT; // delete the object it points to
}

这些问题也值得一读:
Can you remove elements from a std::list while iterating through it?
Doesn't erasing std::list::iterator invalidates the iterator and destroys the object?

关于c++ - 如何访问 std::list 的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15155291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com