public member function
const_reference at ( size_type n ) const;
reference at ( size_type n );
Access element
Returns a reference to the element at position
n in the
vector.
The difference between this member function and member operator function
operator[] is that
vector::at signals if the requested position is out of range by throwing an
out_of_range exception.
Parameters
- n
- Position of an element in the vector.
If this is greater than or equal to the vector size, an exception of type out_of_range is thrown.
Notice that the first element has a position of 0, not 1.
Member type size_type is an unsigned integral type.
Return value
The element at the specified position in the vector.
Member types
reference and
const_reference are the reference types to the elements of the vector container (for the default storage allocation model,
allocator, these are
T& and
const T& respectively).
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
// vector::at
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector<int> myvector (10); // 10 zero-initialized ints
unsigned int i;
// assign some values:
for (i=0; i<myvector.size(); i++)
myvector.at(i)=i;
cout << "myvector contains:";
for (i=0; i<myvector.size(); i++)
cout << " " << myvector.at(i);
cout << endl;
return 0;
}
|
Output:
myvector contains: 0 1 2 3 4 5 6 7 8 9
|
Complexity
Constant.
See also
- vector::operator[]
- Access element (public member function)
- vector::front
- Access first element (public member function)
- vector::back
- Access last element (public member function)