Sunday, November 18, 2012

element access list c++


Because a list does not have random access, it provides only front() and back() for accessing elements directly

Table. Direct Element Access of Lists

Operation
Effect
c.front()
Returns the first element (no check whether a first element exists)
c.back()
Returns the last element (no check whether a last element exists)

As usual, these operations do not check whether the container is empty. If the container is empty, calling them results in undefined behavior. Thus, the caller must ensure that the container contains at least one element.

For example:

std::list<Elem> coll; // empty!
std::cout << coll.front(); // RUNTIME ERROR ? undefined behavior
if (!coll.empty()) 
{
   std::cout << coll.back(); // OK
}

See Also:

No comments:

Post a Comment