Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Thinking In C++, 2nd Edition, Volume 2 Standard Libraries& Advanced Topics - Eckel B..pdf
Скачиваний:
313
Добавлен:
24.05.2014
Размер:
2.09 Mб
Скачать

Of course, there are two things here that you wouldn’t normally do with a deque: first, elements are inserted in the middle, which deque allows but isn’t designed for. Second, calling insert( ) repeatedly with the same iterator would not ordinarily cause an access violation, but the iterator is walked forward after each insertion. I’m guessing it eventually walks off the end of a block, but I’m not sure what actually causes the problem.

If you stick to what deque is best at – insertions and removals from either end, reasonably rapid traversals and fairly fast random-access using operator[ ] – you’ll be in good shape.

Checked random-access

Both vector and deque provide two ways to perform random access of their elements: the 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( ):

//: C04:IndexingVsAt.cpp

// Comparing "at()" to operator[] #include "../require.h"

#include <vector> #include <deque> #include <iostream> #include <ctime> using namespace std;

int main(int argc, char* argv[]) { requireMinArgs(argc, 1);

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();

Chapter 15: Multiple Inheritance

184

Соседние файлы в предмете Программирование