Sunday, August 21, 2011

Using arrays we can store a group of values under a single name. We have C-style arrays in a C++ program. But C-style arrays are inflexible and in some ways awkward to use, so we will use the C++ implementation of the structure, which is a vector.
To use vectors in your code, you need the appropriate library -

Vectors are declared with the following syntax:

vector variable_name (number_of_elements);

The number of elements is optional. You could declare it like this:

vector variable_name;

And that would declare an empty vector — a vector that contains zero elements.


vector values (5); // Declares a vector of 5 integers

vector grades (20); // Declares a vector of 20 doubles

vector names; // Declares a vector of strings,
// initially empty (contains 0 strings)

After a vector has been declared specifying a certain number of elements, we can refer to individual elements in the vector using square brackets to provide a subscript or index, as shown below:


Returns the number of elements in v.

The = operator

You can use the = (assignment) operator to assign one vector to another, for example v1 = v2, so long as they are vectors of the same type (eg both vector or vector). In this case the contents of v1 are overwritten with the contents of v2 and v1 is truncated or extended to be the same length as v2.

push_back() member function
This function allows you to add elements to the end of a vector.

The pop_back() member function

This function removes the last element from the vector.Unfortunately pop_back() doesn't return the value of the popped element.

C++ strings behave (to some extent) like vectors of char

string s = "eyrie";
s[1] = s[0]; // s is now "eerie"
string t = "cat";
char ch = t[0]; // ch is the letter 'c'; note that ch is of type char, not type string
t[0] = t[1];
t[1] = ch; // t is now "act"

Vectors are good at:
  • Accessing individual elements by their position index (constant time).
  • Iterating over the elements in any order (linear time).
  • Add and remove elements from its end (constant time).

No comments:

Post a Comment