What is the difference between deque.at(0) vs deque[0]

0 c++ stl data-structures

So i have this queue

deque<int> deq1(2,10);
Run Code Online (Sandbox Code Playgroud)

I Have accessed the element using 2 way and both of them return the same value

cout<<deq1[0];
cout<<deq1.at(0);
Run Code Online (Sandbox Code Playgroud)

why did them make a special function to do the same thing or is one way better than the other?

小智 5

The only difference is that the function at throw an exception if the index is out of range while the operator[] doesn't make any check. You can see the documentation here

https://en.cppreference.com/w/cpp/container/deque/at

https://en.cppreference.com/w/cpp/container/deque/operator_at