Broad Network


Arrays and Vectors Explanation for app.codility.com in C Plus Plus

Foreword: Category of Article - Technology, Computers, Software, Algorithm

By: Chrysanthus Date Published: 21 Jan 2024

Introduction

An array is a list structure that can be used to store many items in one place. In C++, the items have to be of the same type. Imagine that there is a list of  items; for example, a shopping list. The items are listed in one column or one row on a paper. Such a column or row is conceptually similar to an array. Similarly, if air temperatures for each day in a locality, are planned to be recorded over the next 365 days, then all the temperatures would be recorded in one array. The array will have 365 data entries.

Creating an Array
One way to create an array is as shown in the following program:

    #include <iostream>
    #include <string>
    using namespace std;
    
    string arr[] = {"bread", "butter", "cheese"};
    
    int main(int argc, char** argv)
    {
    
        return 0;
    }

The first and last code segments must be there. The single middle code segment of one statement is what creates the array. It begins with the data type of the elements for the array. In this case, the data type is a string, which should have been included among the pre-processing directives. arr is the name of the array and should be followed by the square brackets, to indicate that the variable is an array. Each shopping item is in a pair of double quotes. These quotes are not the word processor quotes; they are quotes of the text editor. The items are separated by commas. There is no comma after the last item. The array literal or initializer_list is delimited by braces (curly brackets). This is separated from the left  hand side of the statement, by the assignment operator (=).

The first three lines of the program, have to be there. These are pre-processing directives. The first line include the iostream library for input and output (keyboard/terminal). The next line includes the string library, for the string class (data type). The third line used, insists that any namespace used, is of the standard namespace. The fourth line, creates the array, with the array literal on the right of the assignment (=) operator. This has the shopping items as strings. The last code segment is the C++ main function, which has to be there. This function in its current form, has the minimum of its coding. Note the function parameters and the return statement, that have to be there.

The statement (fourth) above that creates the array, is both a declaration and a definition. It is a definition because of the initializer_list (array literal). A declaration is a definition, but a definition is not necessarily a declaration. A definition is an optional sub-part of a declaration, that puts items in memory.

A array can be declared as a simple declaration, without the array literal. In this case it is not really a definition. Also, the number of array items must be included in the square brackets, when it is not a definition. If 3 items are to be in the array, then the simple creation statement would be:

        string arr[3];

In theory, this created array is empty.

Giving an Array, Elements

When an array is created with the initializer_list, the elements (values) are already given. If the array is created with just a simple declaration and not effectively defined, then the array values have to be given, for the different elements as follows:

    #include <iostream>
    #include <string>
    using namespace std;

    string arr[3];
    
    int main(int argc, char **argv)
    {
        arr[0] = "bread";
        arr[1] = "butter";
        arr[2] = "cheese";
    
        return 0;
    }

An array can be seen as different variables next to one another, but with the same name. The actual different variables are differentiated by indexes. Index counting begins from 0, and not 1. The index for a particular value is in square brackets, just after the array name.

Note that though the simple declaration has been made outside of the C++ main() function, the assignment of the values have been made inside the C++ main() function. Assignment of any value is not allowed outside any function, in C/C++ .

Accessing Array Values

Array values in C++ can only be read one-by-one. This is done using the subscript notation (index in square brackets). The syntax is:

    type variable = arrayName[index];

The following code segment will output \93butter\94 after the array has been created:

        string var = arr[1];
        cout << var << endl;

This code segment should  be in the C++ main() function or in any other function, below the creation of the array (with values given). The cout statement sends the value of var to the terminal (screen) and then sends the cursor (I-bar, flashing) to the next line below, at the output.

It has been explained above, how to set (give) value to an array element.

Modifying an Array

The elements of a C++ array can only be modified, one-by-one. The subscript notation is still used. The syntax is:

    arrayName[index] = value;

The value has to be of the same type as all the array elements. The following code segment will output \93chocolate paste\94 instead of \93cheese\94, after the above array has been created:

        arr[2] = "chocolate paste";
        cout << arr[2] << endl;

The output is \93chocolate paste\94. This code segment has to be in the C++ main() function or in any other function, below the creation of the array (with values given).

The index corresponding to the array value \93cheese\94 is 2. \93cheese\94 was replaced.

In C++, once an array has been created, its length cannot be changed. This means that a new item cannot be added after the last item of the array.

The length of an array can also not be reduced, once created.

Iterating over an Array

The do-while-loop
The following program, shows a do-while-loop in C++ :

    #include <iostream>
    #include <string>
    using namespace std;
    
    string arr[] = {"bread", "butter", "cheese"};
    
    int main(int argc, char **argv)
    {
        int i = 0;
        do
            {
                cout << arr[i] << endl;
                i = i + 1;  //increment: add 1
            } while (i<3);
            
        return 0;
    }

Note that the do-while-loop is in the C++ main() function and not outside of any function. The array is not declared (and defined) inside any function. It could still have been defined inside the C++ main() function or any other function.

The output consists of each of the array elements, beginning from the first, then second and then third.

The do-while-loop has a block, delimited by curly brackets (braces). The \93do\94 reserved word is in front of this block. The loop uses a variable, i that is incremented for each pass, through the block.

The statements in the block are executed over and over, in the order typed. The while-condition is that, the block should stop executing, when the value of i is just below 3, that is 2. The first statement in the block prints out an array value. The second statement increments i (adds 1). The block is executed 3 times; when i is 0; i is 1; and i is 2. i was initialized to 1, in front of the do-while-loop.

With the do-while-loop, the block is executed before the while-condition is checked. Note that the do-while-loop construct ends with a semicolon, just after the while-condition \93(i<3)\94.

The While-Loop
The while-loop is similar to the do-while-loop. With the while-loop, the while-condition is checked before the loop body (block) is executed, for each iteration. With the do-while-loop above, the body is executed first, before the while-condition is checked, for each iteration. The following while-loop code segment would replace the above do-while-loop code segment (would do the same thing):

        int i = 0;
        while (i<3)
            {
                cout << arr[i] << endl;
                i += 1;  //increment: add 1
            }

Note that the while-loop construct does not end with a semicolon after, \91}\92. Also note the alternative increment statement, \93i += 1;\94, which is the same as \93i = i + 1;\94

The for-Loop
The while-loop has a difference with the do-while-loop. The for-loop is another way of coding the while-loop. The above while-loop code segment would be coded with the for-loop as follows:

    #include <iostream>
    #include <string>
    using namespace std;
    
    string arr[] = {"bread", "butter", "cheese"};
    
    int main(int argc, char **argv)
    {
        for (int i = 0; i<3; i += 1)
            {
                cout << arr[i] << endl;
            }
            
        return 0;
    }

The for-loop begins with the reserved word, \93for\94 with all letters in lowercase. Then there is the parentheses. In the parentheses, there are three statements, with the last one not ending with a semicolon. The last statement is the increment statement, which has been transferred from the body of the while-loop, to this position. The middle statement is the while-condition. The first statement is the initialization of i to 0; it is no longer outside the construct. There is now only one statement in the body of this loop (for-loop). The output here, is the same as in the previous cases.

Vector

A C++ array has the following limitations:
- It cannot grow or reduce in size once it has been defined.
- It does not have member functions to delete elements or insert elements or add elements (at the back).
- It is a fixed sized list and not really a data structure. So it has other limitations.

A vector is a general purpose data structure that behaves as an array and overcomes the above limitations. This section, only show how to create a vector, how to determine the current size of the vector, and how to add elements at the back of the vector.

Creating a Vector
A vector of the above three strings can be created as in the following program:

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    vector<string> vtr = {"bread", "butter", "cheese"};
    
    int main(int argc, char **argv)
    {
        for (int i = 0; i<vtr.size(); i += 1)
            {
                cout << vtr[i] << endl;
            }
            
        return 0;
    }

Note that the vector library as well as the string library, have been included. The statement that creates the vector is:

    vector<string> vtr = {"bread", "butter", "cheese"};

Note the use of the angle brackets \91<\92 and \91>\92 for the string type. The output is the three strings. An empty vector of strings would be created as follows:

    vector<string> vtr;

Size of the Vector
The following expression would return the size of the vector:

    vtr.size()

where vtr is the name of the vector and size() is a vector class member function.

The push_back() Member Function
push_back() is another vector member function. It takes the argument that is to be added to the back of the vector. It should be used in a function (e.g. the C++ main() function). The following program illustrates this:

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    vector<string> vtr;
    
    int main(int argc, char **argv)
    {    
        vtr.push_back("bread");
        vtr.push_back("butter");
        vtr.push_back("cheese");
        
        for (int i = 0; i<vtr.size(); i += 1)
            {
                cout << vtr[i] << endl;
            }
            
        return 0;
    }
The output is the three elements as before.

Conclusion
An array can be created as the following two code segments show:

    string arr[] = {"bread", "butter", "cheese"};

    string arr[3];
    arr[0] = "bread";
    arr[1] = "butter";
    arr[2] = "cheese";

A vector can be created as the following two code segments show:

    vector<string> vtr = {"bread", "butter", "cheese"};
    
    vector<string> vtr;
    vtr.push_back("bread");
    vtr.push_back("butter");
    vtr.push_back("cheese");

Both the array and the vector can be handled with subscripts (index in square brackets).

Related Links

More Related Links

Cousins

NEXT

Comments