Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created June 2, 2011 16:00
Show Gist options
  • Save mastbaum/1004693 to your computer and use it in GitHub Desktop.
Save mastbaum/1004693 to your computer and use it in GitHub Desktop.
A comparison of using brackets or "at" to access elements of an STL vector
#include<iostream>
#include<vector>
/** There are two ways to access the ith element of an STL vector, the usual
* v[i] syntax or using v.at(i).
*
* The former doesn't check array boundaries, so something like v[v.size()+1]
* works and gives you whatever happens to be sitting in that memory location.
*
* v.at() has the same purpose, but actually throws an exception
* (std::out_of_range) when you're outside array boundaries. This may be
* helpful for debugging buffer overflows, a common source of C++ headaches.
*
* Both v[i] and v.at(i) are of constant complexity.
*/
int main()
{
std::vector<int> a(5);
// Accessing the (a.size()+1)th element with brackets returns junk
std::cout << a[6] << std::endl;
// Accessing the (a.size()+1)th element with at throws an exception
std::cout << a.at(6) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment