How to access the first element of std :: list?

I have a list std::list<T *> *l;. this list is not null and has some meanings. My problem is how to access elements correctly? I do not need to iterate over the list. I just want only the first item.

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

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

or should i also check for null?

if (it != l->end() && (*it))
{
    // accessing T
    int value = (*it)->value();
}
+5
source share
2 answers

If you are forced to use std::list<T*> myList;and let them say it Tis defined as:

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

then just use std::list::frontto access the first element:

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

, myList.front() , . , , .

NULL: , , . , , , , , ( , std::list<T> over std::list<T*> , ).

, NULL . , , , , , undefined. , 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
}

:
std:: list ?
std:: list:: ?

+8

, .

, , NULL .
, .

0

All Articles