cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : STL Containers : vector : at
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
STL Containers
bitset
deque
list
map
multimap
multiset
priority_queue
queue
set
stack
vector
vector
comparison operators
vector::vector
vector::~vector
member functions:
· vector::assign
· vector::at
· vector::back
· vector::begin
· vector::capacity
· vector::clear
· vector::empty
· vector::end
· vector::erase
· vector::front
· vector::get_allocator
· vector::insert
· vector::max_size
· vector::operator=
· vector::operator[]
· vector::pop_back
· vector::push_back
· vector::rbegin
· vector::rend
· vector::reserve
· vector::resize
· vector::size
· vector::swap

-

vector::at 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 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

// 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)

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us