std::vector range checking?

Hi guys I wrote a function to find the highest number in an array and a vector,it should work on both,

when I use the [] operator to pass in my data it works fine no run time exceptions

but when I use .at() function for std::vector it throws an out of range exception

how come std:vector operator[] does not throw an exception if you refer past the size of the vector but when you use the .at() function it throws an exception,

any reason why this is done?

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
#include <vector>

using namespace std;

double highest(double* first,double* last){

   double highest = *first;

   for(double *p = first;p != last;++p){

        if(*p > highest){

            highest = *p;
        }

        cout << "loop" << endl;
   }
   return highest;
}

int main()
{

    double jack[5] = { 7.2,6.1,1.2,9.8,3.2};
    vector<double> jill = {1.2,8.7,6.9,1.3};

    cout << jill.size();

    double jackHigh = highest(&jack[0],jack+5);
    //double jillHigh = highest(&jill.at(0),&jill.at(jill.size())); // out of range exception
    double jillHigh = highest(&jill[0],&jill[jill.size()]); // works fine 
}
how come std:vector operator[] does not throw an exception
It's defined not to.

when you use the .at() function it throws an exception
it's defined to do that.

any reason why this is done?
If you need to use or avoid the range checks, you use the appropriate method as it takes more time (and code) to do the range check.
Last edited on
The .at() function validates the index and throws an exception if it is out of bounds.

operator[] doesn't do any bounds checking. If the index is out of bounds the behaviour is simply undefined (which means there are no guarantees what will happen).
Last edited on
Topic archived. No new replies allowed.