by John
Kopp
Welcome to About.com's C++ tutorial. This lesson introduces
arrays and vectors. Arrays are a data structure that is used to store
a group of objects of the same type sequentially in
memory. They are a built-in part of the C++ language. All the
elements of an array must be the same data type, for example
float,
char,
int,
pointer
to float, pointer to int, a class,
structure or function. Functions provide a way to define
a new operation. They are used to calculate a result or update
parameters. Functions will be covered in a later
lesson. The elements of an array are stored sequentially
in memory. This allows convenient and powerful manipulation of
array elements using pointers. The use of arrays is common in
C and C++ coding and is important to understand well.
Vector is a container class from the C++ standard library.
As is true for an array, it can hold objects of various types.
Vector will also resize, shrink or grow, as elements are
added. The standard library provides access to vectors via
iterators, or subscripting. Iterators are classes that are
abstractions of pointers. They provide access to vectors using
pointer-like syntax but have other useful methods as well. The
use of vectors and iterators is preferred to arrays and
pointers. Common bugs involving accessing past the bounds of
an array are avoided. Additionally, the C++ standard library
includes generic algorithms that can be applied to vectors and
to other container classes.
Defining Arrays An array is defined
with this syntax.
datatype arrayName[size];
| Examples:
int
ID[30];
/* Could be used to store the ID numbers of students
in a class */
float temperatures[31];
/* Could be used to store the daily temperatures in
a month */
char name[20];
/* Could be used to store a character string.
C-style character strings are terminated be the null
character, '\0'. This will be discussed in a later
lesson. */
int
*ptrs[10];
/* An array holding 10 pointers to integer data
*/
unsigned short
int[52];
/* Holds 52 unsigned short integer values
*/
class POINT
{ public: POINT() { x = 0;
y =
0;} ~POINT(); //Accessor
methods declared here private:
int
x; int y; }
POINT
dots[100]; | This last example
declared an array of objects of class POINT. A class to be
used in an array must have a default constructor, that is, a
constructor without arguments. The compiler uses this constructor when
allocating space for the array when it is defined. Next
page > Using
Arrays > Page 1,
2,
3,
4,
5,
6,
7,
8,
9,
10
|