The C++ std::deque::back() function is used to return the reference to the last element in the deque, allowing access to that element. It doesn't remove the element , only provide access.
SyntaxWhen the back() function is invoked on the empty deque, it results in the undefined behaviour.
Following is the syntax for std::deque::back() function.
reference back(); const_reference back() const;Parameters
It does not accepts any parameters
Return valueThis function returns the reference to the last element in the deque.
ExceptionsWhen invoked on the empty deque it results undefined behaviour.
Time complexityThe time complexity of this function is Constant i.e. O(1)
ExampleIn the following example, we are going to consider the basic usage of the back() function.
#include <iostream> #include <deque> int main() { std::deque<char> x = {'A', 'B', 'C', 'D'}; std::cout << "Last Element : " << x.back() << std::endl; return 0; }Output
Output of the above code is as follows −
Last Element : DExample
Consider the following example, where we are going to modify the last element.
#include <iostream> #include <deque> int main() { std::deque<int> a = {1,22,333,4}; a.back() = 4444; std::cout << "After Modification Last Element : " << a.back() << std::endl; return 0; }Output
Following is the output of the above code −
After Modification Last Element : 4444Example
Let's look at the following example, where we are going to use the back() function along with the pop_back().
#include <iostream> #include <deque> int main() { std::deque<char> x = {'A', 'B', 'C', 'D'}; while (!x.empty()) { std::cout << "Last Element: " << x.back() << std::endl; x.pop_back(); } return 0; }Output
If we run the above code it will generate the following output −
Last Element: D Last Element: C Last Element: B Last Element: AExample
Following is the example, where we are going to use the back() function in the loop.
#include <iostream> #include <deque> int main() { std::deque<int> a; for (int x = 1; x <= 4; ++x) { a.push_back(x * 2 ); std::cout << "Last element after push_back : " << a.back() << std::endl; } return 0; }Output
Let us compile and run the above program, this will produce the following result −
Last element after push_back : 2 Last element after push_back : 4 Last element after push_back : 6 Last element after push_back : 8
deque.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4