(C++) Deck: Differences between position access types

Asked

Viewed 108 times

0

I am implementing the Backpack Problem with Dynamic Programming in C++ and chose the deck to build my list. Studying on it, I noticed these two different ways to access a specific position of the list:

//Retorna o item i da lista mydeque
mydeque[i]
mydeque.at(i)

What is the real difference between the two, since at first sight both are identical?

2 answers

1


std::deque and std::vector have two ways to access elements in indexed form:

  • By the Elder brackets []
  • For the function of a member at

The basic difference between the two is that the function at check the index, casting an exception (std::out_of_range) in case of access beyond the size of the container. The bracketed operator assumes that it will always be invoked with a valid index.

  • Then the at member function prevents the program from accessing prohibited memory areas?

  • Yes, in exchange for a small performance penalty, because each access is made a test. And you also have to treat the exception, otherwise your program will be terminated anyway. Using the bracketed operator you are responsible for ensuring that there will be no invalid access.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.