[prog] C++ STL at() function

Elizabeth Barham lizzy at soggytrousers.net
Sun May 11 15:24:36 EST 2003


ed writes:

> As I understand it, the Standard Template Library function
> at() is used to insert an element into a vector and also
> to check for an out_of_range error.  Sounds good, and it
> would be really useful, but I can't get it to work.
> The compile time GNU error is:
>  no matching function to call to
> "vector<int>, allocator<int>>::at(int)"    duh?
> I'm using the GNU C++ compiler on Red Hat 7.3.
> g++ -Wall -W -o at_test at_test.cpp
>   Could someone tell me what I'm doing wrong?

My guess is that the at(int) function was not implemented in the late
g++ 2.x version of the STL. However, on my debian distribution
installation, your code compiles practically verbatim using v3 of g++:

     $ g++-3.0 test2.cpp 
     $ ./a.out 
     Error  vector

The notable changes to your code are adding

  using namespace std;

directly beneath the #include directives and modifying the error
message somewhat:

     cout << "Error  " << e.what() << endl;

For completeness:

#include <iostream>
#include <vector>
#include <algorithm>  // not sure I need this
#include <stdexcept>  // for out_of_range

using namespace std;

int main() {
   int apple[ 6 ] = { 1,2,3,4,5,6 };
   vector< int > v ( apple, apple + 6 ); // create and initialize vector v
   try {
       v.at( 100 ) = 66;   // deliberate error
   }
   catch( out_of_range e )
   {
     cout << "Error  " << e.what() << endl;
   }
   return 0;
}

Regards, Elizabeth


More information about the Programming mailing list