0

So i have this queue

deque<int> deq1(2,10);

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

cout<<deq1[0];
cout<<deq1.at(0);

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

Sarah M.
  • 13
  • 1

1 Answers1

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

Stiven
  • 309
  • 1
  • 9
  • 1
    I'd like to insist on the fact that throwing an exception is a good thing, not a bad thing, and you should probably prefer `at` to `operator[]`. If you call `operator[]` with a wrong index, it will cause problems, but they will be much harder to track down. – Stef Jul 27 '22 at 07:59
  • @Stef If you know that you won't use an index outside the range (e.g. it doesn't depend on any user input, file input, etc...) and you care about performances, using `operator[]()` is wiser than performing an unnecessary check with `at()`. The thing is, there is no better or worse version, each one has its own/proper usages, hence why there are two functions instead of one. – Fareanor Jul 27 '22 at 08:48
  • @Fareanor I actually agree with you, but my concern was that this answer could make it sound like "`at` risks producing an exception, whereas `[]` doesn't have that risk, so `[]` is safer than `at`". Which is the opposite of the truth. Hence my comment. If someone comes to this page because they couldn't understand the difference between `at` and `[]` from the documentation, I'm guessing the difference in performance between `[]` and `at` isn't the most relevant issue to them. – Stef Jul 27 '22 at 08:59
  • @Stef My answer was not intended to promote one or another solution. May be you can help me to improve my answer! – Stiven Jul 27 '22 at 09:12