C++ <iterator> - cend() Function
The C++ <iterator> cend() function returns an iterator pointing to the past-the-last element in the sequence. The container's object is always treated as constant qualified and if the sequence is a standard container, the function always returns a const_iterator.
The past-the-last element of a sequence is the theoretical element that follows the last element. It does not point to any element, and hence could not be dereferenced.
These function templates are defined in multiple headers which are: <iterator>, <array>, <deque>, <forward_list>, <list>, <map>, <regex>, <set>, <string>, <string_view>, <unordered_map>, <unordered_set> and <vector>.
Note: A const_iterator is an iterator that points to constant value. The difference between iterator and const_iterator is that the const_iterator cannot be used to modify the content it points to, even if the vector element is not itself constant.
Syntax
template <class Container> constexpr auto cend (const Container& cont) noexcept -> decltype (end(cont));
Parameters
cont |
Specify a container or view with a end member function. |
Return Value
Returns an iterator to the past-the-last element of the sequence. The container's object is always treated as constant qualified and if the sequence is a standard container, the function always returns a const_iterator.
Example:
In the example below, the cend() function is used to iterate over an array to insert all elements of the array into a vector.
#include <iostream> #include <iterator> #include <vector> using namespace std; int main (){ int arr[] = {10, 20, 30, 40, 50}; vector<int> vec; //iterate over array to insert all elements //of the array into an empty vector for(auto it = cbegin(arr); it != cend(arr); ++it) vec.push_back(*it); //print the content of the vector cout<<"vec contains: "; for(auto it = cbegin(vec); it != cend(vec); ++it) cout<<*it<<" "; return 0; }
The output of the above code will be:
vec contains: 10 20 30 40 50
❮ C++ <iterator> Library