Replacing Arrays Using the vector Class in C++

A vector can be used to replace arrays. Vectors are more flexible than arrays, but arrays are more efficient than vectors.

A vector object can be used like an array, but there are some differences. Table 12.1 lists their similarities and differences.

Both arrays and vectors can be used to store a list of elements. Using an array is more effi­cient if the size of the list is fixed. A vector is a resizable array. The vector class contains many member functions for accessing and manipulating a vector. Using vectors is more flexi­ble than using arrays. In general, you can always use vectors to replace arrays. All the examples in the preceding chapters that use arrays can be modified using vectors. This section rewrites Listing 7.2, DeckOfCards.cpp, and Listing 8.1, PassTwoDimensionalArray.cpp, using vectors.

Recall that Listing 7.2 is a program that picks four cards randomly from a deck of 52 cards. We use a vector to store the 52 cards with initial values 0 to 51, as follows:

const int NUMBER_OF_CARDS = 52;

vector<int> deck(NUMBER_OF_CARDS);

// Initialize cards

for (int i = 0; i < NUMBER_OF_CARDS; i++)

deck[i] = i;

deck[0] to deck[12] are Clubs, deck[13] to deck[25] are Diamonds, deck[26] to deck[38] are Hearts, and deck[39] to deck[51] are Spades. Listing 12.9 gives the solu­tion to the problem.

Listing 12.9   DeckOfCardsUsingVector.cpp

1 #include <iostream>
2
#include <vector>
3
#include <string>
4
#include <ctime>

5 using namespace std;
6
7
const int NUMBER_OF_CARDS = 52;
8 string suits[
4] = {“Spades”, “Hearts”, “Diamonds”, “Clubs”};
9 string ranks[
13] = {“Ace”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”,
10
“10”, “Jack”, “Queen”, “King”};
11
12
int main()
13 {
14    vector<
int> deck(NUMBER_OF_CARDS);
15
16   
// Initialize cards
17    for (int i = 0; i < NUMBER_OF_CARDS; i++)
18    deck[i] = i;
19
20   
// Shuffle the cards
21    srand(time(0));
22   
for (int i = 0; i < NUMBER_OF_CARDS; i++)
23    {
24       
// Generate an index randomly
25       int index = rand() % NUMBER_OF_CARDS;
26       
int temp = deck[i];
27       deck[i] = deck[index];
28       deck[index] = temp;
29    }
30
31   
// Display the first four cards
32    for (int i = 0; i < 4; i++)
33    {
34        cout << ranks[deck[i] %
13] << ” of ” <<
35        suits[deck[i] /
13] << endl;
36    }
37
38   
return 0;
39 }

This program is identical to Listing 7.2, except that line 2 includes the vector class and line 14 uses a vector to store all cards instead of an array. Interestingly, the syntax for using arrays and vectors is very similar, because you can use indexes in the brackets to access the elements in a vector, which is the same as for accessing array elements.

You could also change the arrays suits and ranks in lines 8-10 to vectors. If so, you have to write many lines of code to insert the suits and ranks to the vector. The code is simpler and better using arrays.

Recall that Listing 8.1 creates a two-dimensional array and invokes a function to return the sum of all elements in the array. A vector of vectors can be used to represent a two­dimensional array. Here is an example to represent a two-dimensional array with four rows and three columns:

vector<vector<int> > matrix(4); // four rows

for (int i = 0; i < 4; i++)

matrix[i] = vector<int>(3);

matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;
matrix[
1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6;
matrix[
2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9;
matrix[
3][0] = 10; matrix[3][1] = 11; matrix[3][2] = 12;

Listing 12.10 revises Listing 8.1, PassTwoDimensionalArray.cpp, using vectors.

Listing I2.I0 TwoDArrayUsingVector.cpp

1 #include <iostream>
2
#include <vector>
3
using namespace std;
4
5
int sum(const vector<vector<int>>& matrix)
6 {
7     
int total = 0;
8     
for (unsigned row = 0; row < matrix.size(); row++)
9     {
10       
for (unsigned column = 0; column < matrix

.size(); column++)
11        {
12           total += matrix
[column];
13        }
14    }
15
16    return total;
17 }
18
19
int main()
20 {
21     vector<vector<
int>> matrix(4); // Four rows
22
23     
for (unsigned i = 0; i < 4; i++)
24     matrix[i] = vector<
int>(3); // Each row has three columns
25
26     matrix[
0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;
27     matrix[
1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6;
28     matrix[
2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9;
29     matrix[
3][0] = 10; matrix[3][1] = 11; matrix[3][2] = 12;
30
31    cout <<
“Sum of all elements is ” << sum(matrix) << endl;
32
33   
return 0;
34 }

The variable matrix is declared as a vector. Each element of the vector matrix[i] is another vector. So, matrix[i] [j] represents the ithrow andjth column in a two-dimensional array.

The sum function returns the sum of all elements in the vector. The size of the vector can be obtained from the size() function in the vector class. So, you don’t have to specify the vector’s size when invoking the sum function. The same function for two-dimensional array requires two parameters as follows:

int sum(const int a[][COLUMN_SIZE], int rowSize)

Using vectors for representing two-dimensional arrays simplifies coding.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *