Namespaces
Variants
Views
Actions

Difference between revisions of "Template:cpp/container/back"

From cppreference.com
m (Text replace - "/sidebar" to "/navbar")
(I'm assuming that calling back on an empty container is UB as well, b/c we'd be dereferencing an invalid iterator)
Line 11: Line 11:
  
 
Returns reference to the last element in the container.  
 
Returns reference to the last element in the container.  
 +
 +
Calling {{tt|back}} on an empty container is undefined.
  
 
===Parameters===
 
===Parameters===
Line 20: Line 22:
 
===Complexity===
 
===Complexity===
 
Constant
 
Constant
 +
 +
===Notes===
 +
For a container {{tt|c}}, the expression {{c|return c.back();}} is equivalent to {{c|{ auto tmp {{=}} c.end(); --tmp; return *tmp; } }}
  
 
===Example===
 
===Example===

Revision as of 05:40, 26 June 2012

Template:ddcl list begin <tr class="t-dcl ">

<td class="t-dcl-nopad">
reference back();
</td>

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> <tr class="t-dcl ">

<td class="t-dcl-nopad">
const_reference back() const;
</td>

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> Template:ddcl list end

Returns reference to the last element in the container.

Calling back on an empty container is undefined.

Contents

Parameters

(none)

Return value

reference to the last element

Complexity

Constant

Notes

For a container c, the expression return c.back(); is equivalent to { auto tmp = c.end(); --tmp; return *tmp; }

Example

The following code uses back to display the last element of a std::{{{1}}}<char>:

#include <{{{1}}}>
#include <iostream>
 
int main()
{
    std::{{{1}}}<char> letters {'o', 'm', 'g', 'w', 't', 'f'};
 
    if (!letters.empty()) {
        std::cout << "The last character is: " << letters.back() << '\n';
    }  
}

Output:

The last character is f

See also

Template:cpp/container/dcl list front