Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Checked random access

Both vector and deque provide two random access functions: the indexing operator (operator[ ]), which you ve seen already, and at( ), which checks the boundaries of the container that s being indexed and throws an exception if you go out of bounds. It does cost more to use at( ):

//: C07:IndexingVsAt.cpp
// Comparing "at()" to operator[].
#include <ctime>
#include <deque>
#include <iostream>
#include <vector>
#include "../require.h"
using namespace std;
 
int main(int argc, char* argv[]) {
long count = 1000;
int sz = 1000;
if(argc >= 2) count = atoi(argv[1]);
if(argc >= 3) sz = atoi(argv[2]);
vector<int> vi(sz);
clock_t ticks = clock();
for(int i1 = 0; i1 < count; i1++)
for(int j = 0; j < sz; j++)
vi[j];
cout << "vector[] " << clock() - ticks << endl;
ticks = clock();
for(int i2 = 0; i2 < count; i2++)
for(int j = 0; j < sz; j++)
vi.at(j);
cout << "vector::at() " << clock()-ticks <<endl;
deque<int> di(sz);
ticks = clock();
for(int i3 = 0; i3 < count; i3++)
for(int j = 0; j < sz; j++)
di[j];
cout << "deque[] " << clock() - ticks << endl;
ticks = clock();
for(int i4 = 0; i4 < count; i4++)
for(int j = 0; j < sz; j++)
di.at(j);
cout << "deque::at() " << clock()-ticks <<endl;
// Demonstrate at() when you go out of bounds:
try {
di.at(vi.size() + 1);
} catch(...) {
cerr << "Exception thrown" << endl;
}
} ///:~
 

As you saw in Chapter 1, different systems may handle the uncaught exception in different ways, but you ll know one way or another that something went wrong with the program when using at( ), whereas it s possible to remain ignorant when using operator[ ].

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire