Deitel & Associates, Inc. Logo

Back to
digg.png delicious.png blinkit.png furl.png
C++ How to Program, 5/e

© 2005
pages: 1500
Buy the Book!
Amazon logo
InformIT logo

STL containers are data structures capable of storing objects of any type. There are three major categories of containers—sequence containers, associative containers and container adapters. The sequence containers represent linear data structures. The following article discusses the vector sequence container. Also see the related articles that introduce sequence containers and discuss the list sequence container and the deque sequence container.

[Note: This tutorial is an excerpt (Sections 23.2) of Chapter 23, Standard Template Library (STL), from our textbook C++ How to Program, 5/e. These tutorials may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., C++ HOW TO PROGRAM, ©2005, pp.1124-1136. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

23.2.1 vector Sequence Container

Class template vector provides a data structure with contiguous memory locations. This enables efficient, direct access to any element of a vector via the subscript operator [], exactly as with a C or C++ “raw” array. Class template vector is most commonly used when the data in the container must be sorted and easily accessible via a subscript. When a vector’s memory is exhausted, the vector allocates a larger contiguous area of memory, copies the original elements into the new memory and deallocates the old memory.

Performance Tip
Performance Tip 23.7
Choose the vector container for the best random-access performance.
Performance Tip
Performance Tip 23.8
Objects of class template vector provide rapid indexed access with the overloaded subscript operator [] because they are stored in contiguous memory like a C or C++ raw array.
Performance Tip
Performance Tip 23.9
It is faster to insert many elements at once than one at a time.

An important part of every container is the type of iterator it supports. This determines which algorithms can be applied to the container. A vector supports random-access iterators—i.e., all iterator operations shown in Fig. 23.10 can be applied to a vector iterator. All STL algorithms can operate on a vector. The iterators for a vector are normally implemented as pointers to elements of the vector. Each STL algorithm that takes iterator arguments requires those iterators to provide a minimum level of functionality. If an algorithm requires a forward iterator, for example, that algorithm can operate on any container that provides forward iterators, bidirectional iterators or random-access iterators. As long as the container supports the algorithm’s minimum iterator functionality, the algorithm can operate on the container.

Page 1 | 2 | 3 | 4 | 5 | 6

Tutorial Index