Deque::at
deque::at is used to return a reference to the element at position x in the deque container object. Deque::at automatically checks whether x is within the bounds of valid elements in the container or not.
Syntax:
at (size_type n);
Parameters:
Position of the element to be fetched.
Return Value: Direct reference to the element at the given position.
In this container all the iterators are valid. The header file for using deque::at is <deque>.
Exception:
- If an exception is thrown, there are no changes in the container.
- It throws out_of_range if n is out of bounds.
Below is the C++ program to implement deque::at:
C++
// C++ program to implement // deque::at #include <iostream> #include <deque> using namespace std; // Driver code int main () { // 10 zero-initialized unsigneds deque< int > gfg (10); // Here we have assigned some values for ( int i = 0; i < gfg.size(); i++) gfg.at(i) = i; cout << "Elements after using deque::at -:" ; for ( int i = 0; i < gfg.size(); i++) { cout << ' ' << gfg.at(i); } cout << endl; return 0; } |
Elements after using deque::at -: 0 1 2 3 4 5 6 7 8 9
- Time Complexity: O(1)
- Space Complexity: O(1)
Difference Between deque::assign and deque::at in C++
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. Here we will see the difference between deque::assign and deque::at in C++.