Logo

Programming-Idioms

History of Idiom 165 > diff from v48 to v49

Edit summary for version 49 by zaflick:
[Cpp] Iterator approach was too verbose for the simple case.

Version 48

2019-09-27, 02:31:33

Version 49

2019-09-27, 02:42:50

Idiom #165 Last element of list

Assign to variable x the last element of list items.

Idiom #165 Last element of list

Assign to variable x the last element of list items.

Imports
#include<vector>
Imports
#include<vector>
Code
std::vector<int> items;
auto last = items.crend() != items.crbegin() ? *items.crbegin() : -1;
Code
std::vector<int> items;
int last = items.back();
Comments bubble
Use iterators to iterate through containers
Comments bubble
The vector must not be empty.