at
Syntax: #include <deque> TYPE& at( size_type loc ); const TYPE& at( size_type loc ) const; The at() function returns a reference to the element in the dequeue at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the dequeue. For example, consider the following code: vector<int> v( 5, 1 ); for( int i = 0; i < 10; i++ ) { cout << "Element " << i << " is " << v[i] << endl; } This code overrunns the end of the vector, producing potentially dangerous results. The following code would be much safer: vector<int> v( 5, 1 ); for( int i = 0; i < 10; i++ ) { cout << "Element " << i << " is " << v.at(i) << endl; } Instead of attempting to read garbage values from memory, the at() function will realize that it is about to overrun the vector and will throw an exception. Related topics:
|