[C ++ exploration tour] Part 1 Lesson 9: array mighty, dynamic and static Integration

Source: Internet
Author: User

[C ++ exploration tour] Part 1 Lesson 9: array mighty, dynamic and static Integration

 

 

Introduction

1. Part 1The9Course:Array mighty, combination of dynamic and static

2. Part I Lesson 10: Reading and Writing files

 

Array mighty, combination of dynamic and static

In Lesson 8 [C ++ exploration journey] Part I: passing value references, file source, we learned different transfer modes of function parameters: it also learns how to use header files and source files to better organize projects.

 

In many programs, we need to use multiple variables of the same type. For example, the User Name List of a website (generally 'string' type), or the top 10 optimal scores of a game (generally 'int' type ).

 

Similarly, C ++, like most programming languages, can combine multiple data of the same type. As described in the title of this lesson, we call this data form an array.

 

We will learn two types of arrays. An array is used to know the number of elements contained in it in advance, for example, the first 10 optimal scores in a game, and the number of elements in the other array changes, for example, the User Name List of a website.

 

Smart as you might expect: it is relatively easy to use arrays that know the number of elements in advance, so we should start with this type.

 

Static Array

 

In the introduction of this lesson, we have discussed the general purpose of Arrays:Stores a series of variables of the same type.

 

As the saying goes: Good memory is worse than bad writing. I think: a good explanation is not as bad as an example. Therefore, we will give you a "chestnut ":

 

Instance

 

If you want to display the top five scores of a game, you generally need two lists:List of contestant names and their scores.

 

Therefore, we need to declare 10 variables.To write the information to the memory.

 

For example:

 

string bestPlayerName1("Albert Einstein");string bestPlayerName2("Isaac Newton");string bestPlayerName3("Marie Curie");string bestPlayerName4("Thomas Edison");string bestPlayerName5("Alfred Nobel");int bestScore1(118218);int bestScore2(100432);int bestScore3(87347);int bestScore4(64523);int bestScore5(31415);

 

It is not easy to display the five scores:

 

cout << "1) " << bestPlayerName1 << " " << bestScore1 << endl;cout << "2) " << bestPlayerName2 << " " << bestScore2 << endl;cout << "3) " << bestPlayerName3 << " " << bestScore3 << endl;cout << "4) " << bestPlayerName4 << " " << bestScore4 << endl;cout << "5) " << bestPlayerName5 << " " << bestScore5 << endl;

 

As you can see, it is very difficult to show only five highest scores. If you want to display the highest score of 100, you need to declare 200 variables (100 contestant names and 100 highest scores), and then write 100 lines of cout... The baby is bitter, but the baby does not say.

 

 

Therefore, we urgently need array help: With array, we can declare 100 highest scores and 100 contestant names at a time. In memory, we can apply to store 100 int-type variables and 100 string-type variables at a time. Great, isn't it?

 

Of course, the elements in the same number of groups must be correlated so that our program can be properly planned. It is not appropriate to place your dog's age and number of people on the Internet in the same array, although they are all int-type variables.

 

In the preceding example, we have to apply 100 int variables and 100 string variables each. Therefore, we need two arrays to store them separately. 100 is the size of the two arrays. This size does not change in the entire program. We call it a static array. For the moment, we only need to use static arrays.

 

Declare static Arrays

 

In C ++, a variable is identified by its name and type. Since the array is a set of the same variables, this rule is still valid. But we need to add another identifier: the size of the array.

 

Declaring an array is similar to declaring a variable. As follows:

 

Type name [size];

 

Write from left to right: type, name, brackets,Fill in the array size in brackets (number of elements)

 

See the following example:

 

# Include
 
  
Using namespace std; int main (){? Int bestScores [5]; // declare an array containing five int variables, named bestScores double angles [3]; // declare an array containing three double variables, name: angles return 0 ;}
 

 

Let's use the memory diagram to better understand it:

 

 

In, we can see that two large spaces are allocated in the memory. Their respective labels are bestScores and angles. One has five "Drawers" and the other has three "Drawers ". For the moment, we haven't assigned values to the variables in these drawers, so their values are arbitrary, as shown in the question mark.

 

We can also use a const variable as the array size, as long as the const variable type is int or unsigned int. For example:

 

Int const arraySize (20); // The array size is 20 double angles [arraySize];

 

To use the size of a static array, you must use the const variable. If you use a common variable, an error occurs.

 

We recommend that you try not to use numbers as the size of the array. Using the const variable is a good habit.

 

Now that we have applied for space in the memory, we only need to use it.

 

Elements accessing the Array

 

Since each element in the array is a variable, its usage is no different from that of the general variable. However, to access these elements in the array, you must use a special method: Specify the array name and element number. In the previous example, we declared int bestScores [5];

 

Therefore, the bestScores array has five elements numbered from the first to the fifth.

 

To access these elements, we use the format: array name [element number]

 

The element number here is called a subscript.

 

Note:The subscript of the first element in the array is 0, rather than starting from 1.

 

Therefore, the subscript of the first element is 0, and the number of the second element is 1, which increases sequentially.

 

If I want to access the 3rd elements in the bestScores array, I will use the following:

 

bestScores[2] = 5;

 

Therefore, if we want to assign values to every element of bestScores like the previous example program, we need to do this:

 

Int const bestScoreNumber (5); // the size of the array int bestScores [bestScoreNumber]; // declare the array bestScores [0] = 118218; // fill bestScores [1] = 1st; // fill bestScores [2] = 100432; // fill bestScores [3] = 3rd; // fill bestScores [4] = 64523; // fill 4th elements in the array

 

Traverse Arrays

 

An array is powerful in that we can use loops to easily traverse elements in the array.

 

Since we know the size of the static array in advance, we can use a for loop to traverse it.

 

# Include
 
  
# Include
  
   
Using namespace std; int main () {int const bestScoreNumber (5); // the size of the array int bestScores [bestScoreNumber]; // declare the array bestScores [0] = 118218; // fill bestScores [1] = 1st; // fill bestScores [2] = 100432; // fill bestScores [3] = 3rd; // fill bestScores [4] = 64523; // fill in the 5th elements of the array for (int I (0); I <bestScoreNumber; ++ I) {cout <bestScores [I] <endl ;} return 0 ;}
  
 

The values of variable I are 0, 1, 2, 3, 4 in sequence. Therefore, the values passed to cout are bestScores [0], bestScores [1], until bestScores [4].

 

Note: The subscript of an array element must not exceed the number of array elements minus 1. Otherwise, an array subscript out-of-bounds error will be reported. For example, the size of the preceding array is 5, so the subscript of the array element is 4 at the maximum.

 

You will gradually find that in C ++ programming, the combination of arrays and for loops will become a good tool that you often use.

 

Arrays and functions

 

I hope you haven't forgotten what the function is, or it will hurt me too much...

 

In any case, let's review the functions.

 

However, you will see that static arrays and functions are not so good friends.

 

The first restriction is that we cannot create a function that returns static arrays.

 

The second restriction is that when static arrays are used as function parameters, they are always transmitted in reference mode. And do not need to add the & Symbol: all are automatic. This means that when we pass an array to the function as a parameter, the function can modify this array.

 

The following is a function style of the array:

 

void function(int array[]){ //…}

 

As shown above, the brackets in the array do not contain the array size.

 

As mentioned above, we need to know its size to traverse an array. In the above function style, we do not know the size of the array, so we can only add one parameter: function size. As follows:

 

void function(double array[], int arraySize){ //…}

 

I know, it's a bit frustrating. But you can't blame me. After all, I didn't invent C ++.

 

For a short exercise, I hope you can write a function to calculate the average value of all elements in the array.

 

The following is my version:

 

/** Function for calculating the average value of array elements *-array: array for calculating the average value *-arraySize: array size */double average (double array [], int arraySize) {double average (0); for (int I (0); I

 

We have already talked about static arrays. Let's talk about dynamic arrays.

 

Dynamic Array

 

As mentioned before, we will introduce two types of Arrays: static array, fixed array size, and variable size, this type of array is a dynamic array. However, since they are all arrays, some concepts are still common.

 

Declare a dynamic array

 

Static arrays and dynamic arrays have many differences.

 

The first difference is that at the beginning of the program, we need to add a line

 

#include 
  

 

In this way, we can use dynamic arrays. (Of course, we should generally use the new method to create a dynamic array. We will only talk about it in Part 2: object orientation. Currently, we only use vector to represent a dynamic array)

 

The English word "vector" means "vector.

 

The second difference lies in the array declaration method.

 

The format of declaring a dynamic array is as follows:

 

Vector <type> name (size );

 

For example, to declare a dynamic array containing five int variables, we can do this:

 

# Include
  
   
# Include
   
    
// Do not forget using namespace std; int main () {vector
    
     
Array (5); return 0 ;}
    
   
  

 

Three points need to be distinguished:

 

In the case of dynamic arrays, the type is no longer at the beginning, which is different from the declaration method of variables and static arrays. First, write the keyword vector.

We use a pair of strange angle brackets <>, where the write type

We put the array case in parentheses, while the static array is the array case in brackets.

 

This also shows that the dynamic array and static array are different. However, you will see that the way to traverse the array is similar.

 

Before that, there are two tips to learn.

 

  1. We can quickly and directly fill in all the elements of the dynamic array, just add the second parameter to the parentheses, as shown below:

    Vector Array (5, 3); // create a dynamic array, which contains 5 int variables with values of 3

    Vector NameList (12, "anonymous"); // creates a dynamic array containing 12 string variables with the value "anonymous"

    We can declare a dynamic array without elements, just remove the parentheses:

    Vector Array; // create a dynamic array of the double type with 0 Elements

     

    So you have to ask: what is the significance of creating a dynamic array with 0 elements?

     

    Do you still remember the nature of dynamic arrays? The array size can be changed. So we can then add elements to it. Wait and you will know.

     

    Elements accessing Dynamic Arrays

     

    Although the dynamic array declaration method is very different from the static array, the method for accessing its elements is similar. We re-use brackets. The subscript of the first element also starts from 0.

     

    Therefore, we can rewrite our previous example and use a dynamic array vector:

     

    Int const bestScoreNumber (5); // array size vector
        
         
    BestScores (bestScoreNumber); // declare the dynamic array bestScores [0] = 118218; // fill in the 1st elements of the array bestScores [1] = 100432; // fill bestScores [2] = 2nd; // fill bestScores [3] = 87347; // fill in the 4th elements of the array bestScores [4] = 31415; // fill in the 5th elements of the array
        

     

    Change the size of a dynamic array

     

     

    The key to the knowledge point of the dynamic array is: Changing the array size.

     

    First, learn how to add elements at the end of the array.

     

    We need to use the push_back () function. The usage is as follows:

     

    Vector
        
         
    Array (3, 2); // create a dynamic array named array and the size is 3. Each element is an int variable and the value is 2array. push_back (8); // Add a new element (4th) to the end of the array. The value is 8.
        

     

    Use the memory diagram to explain what happened above:

     

     

    We can see that a new element is added to the end of the array.

     

    Of course, we can use the push_back function to add multiple elements, as shown below:

     

    Vector
        
         
    Array (3, 2); // create a dynamic array named array and the size is 3. Each element is an int variable and the value is 2array. push_back (8); // Add a new element (4th) to the end of the array. Its value is 8 array. push_back (7); // Add a new element (5th) to the end of the array with the value of 7array. push_back (14); // Add a new element (6th) to the end of the array. Its value is 14 // now, the array contains the following elements: 2228714
        

     

    Can a vector dynamic array insert only elements but not delete them?

     

    Of course not. The author of C ++ has long thought of it.

     

    We can use the pop_back function to delete the last element of the dynamic array. The usage is similar to the push_back function, except that there is no parameter in the parentheses of the pop_back function.

     

    Vector
        
         
    Array (3, 2); array. pop_back (); // delete an element, with only two elements left: array. pop_back (); // delete one element, with only one
        

     

    Of course, do not overhead it. After all, a dynamic array cannot contain less than 0 elements.

     

    Since the size of the dynamic array is variable, how can we know its size in real time? Fortunately, a function in the vector can use: size (), which can return the size of the array.

     

    Vector
        
         
    Array (5, 4); // array intconstsize (array. size (); // The size const variable is the size of the array, so the value is 5
        

     

    Dynamic Arrays and functions

     

    Compared with static arrays, it is much easier to pass dynamic arrays to functions as parameters.

     

    Because of the size () function, we do not need to add the second parameter to specify the size of the array.

     

    As follows:

     

    // A parameter is the voidfunction (vector
        
         
    Array ){//...}
        

     

    It's easy, isn't it? But we can do better.

     

    In previous courses, we have said that referencing and passing can prevent copying and optimize the code to a certain extent. In fact, if the array contains many elements, it will take a long time to copy them. Therefore, we can use the following tips:

     

    // A parameter is the voidfunction (vector
        
         
    Const & array ){//...}
        

     

    Because const is used, this dynamic array cannot be changed in the function; because the & reference symbol is used, this dynamic array will not be copied.

     

    To call a function whose parameter is a dynamic array, it is also very simple:

     

    Vector
        
         
    Array (); function (array); // transmits the dynamic array to the function defined above
        

     

    We learned how to use the. h header file to store the function prototype. Therefore, we need to use the following:

     

    # IfndefARRAY_H_INCLUDED # defineARRAY_H_INCLUDED # include
        
         
    // Introduce the vector header file voidfunction (std: vector
         
          
    & Array); // std: # endif // ARRAY_H_INCLUDED must be added before the vector.
         
        

     

    Of course, we can also create a function that returns a dynamic array. I believe you already know how to do this:

     

    vector
        
         function(inta){//...}
        

     

    Multi-dimensional array

     

    We can create an int-type array, that is, each element in the array is an int variable. We can also create double-type arrays and string-type arrays.

     

    We can even create arrays.

     

    I think you may frown and think: array, what is this and what is it?

     

    First, let's take a look at the memory diagram:

     

     

    The large yellow lattice is an array variable. This array consists of five separate smaller grids, and each smaller grid has four smaller grids.

     

    The array is called a multi-dimensional array. The arrays we previously touched are all one-dimensional.

     

    Declare multi-dimensional arrays

     

    To declare such a multi-dimensional array, we need to use multiple brackets to enclose the corresponding case of different dimensions in brackets, one by one. As follows:

     

    Type array name [size 1] [size 2];

     

    Therefore, to declare the two-dimensional array shown in the memory diagram above, we can do this:

    intarray[5][4];

     

    Or, to be more optimized, use the const variable:

     

    intconstsizeX(5);intconstsizeY(4);intarray[sizeX][sizeY];

     

    Element used to access multi-dimensional arrays

     

    I believe that there is no need to explain it too much. You can also guess how to access the elements of multi-dimensional arrays.

     

    For example, array [0] [0] is the lattice in the lower left corner of the yellow array above; array [0] [1] corresponds to the lattice above it; array [1] [0] corresponds to the grid on the right. And so on.

     

    How can I access the lattice in the upper right corner?

     

    It is not difficult, that is, array [4] [3]

     

    Further Exploration

     

    Of course, we can create three-dimensional, four-dimensional, or even more multidimensional arrays. For example:

     

    doublesuperArray[5][4][6][2][7];

     

    I don't want to draw the above array because it is too difficult. However, when writing a program, we seldom use arrays larger than three dimensions.

     

    The multidimensional array shown above is a static multidimensional array. We can also create a variable-size multi-dimensional array, which requires vector. For example, to create a two-dimensional dynamic array, you can write it as follows:

     

    Vector
        
         
    > Array; array. push_back (vector
         
          
    (5); // Add a row to the two-dimensional array, which contains five elements: array. push_back (vector
          
           
    (3, 4); // Add a row to the two-dimensional array. This row contains three elements and each element has a value of 4.
          
         
        

    Each row of a multidimensional dynamic array can have different sizes. We can still use subscript to access different elements.

     

    Array [0]. push_back (8); // Add an element with a value of 8 to the first row.

     

    Like a multi-dimensional static array, the element of a multi-dimensional dynamic array can be accessed as follows, but you need to confirm that this element exists:

     

    Array [2] [3] = 9; // change the value of the element in column 3rd of row 4th to 9.

     

    We can see that multi-dimensional dynamic arrays are not so easy to use and are not effectively using memory.

     

    For multi-dimensional arrays, we still use a large number of static arrays.

     

    String: character array

     

    Before we end this lesson, we also need to secretly tell you that the strings we have been using are actually arrays!

     

    It is not easy to see this when we declare a string type variable. In fact, strings are similar to character arrays and are similar to vector (dynamic array.

     

    Of course, after learning the second part (Object-Oriented), we will know that string is actually a class. I will not go into it for the moment.

     

    Character in the access string

     

    Understanding that strings are character arrays allows us to learn how to access each character or even rewrite them. We still use subscript for access.

     

    # Include
        
         
    # Include
         
          
    Usingnamespacestd; intmain () {stringuserName ("Julien"); cout <"you are" <
          
           

     

    Run and output:

     

    You are Julien.

    Ah, no. You are Lucien.

     

    It's amazing, isn't it? But we can do better.

     

    String-related functions

     

    We can use the size () function to know the number of characters in the string variable, and use the push_back () function to add characters to the end of the string variable. Just like operating a vector.

     

    Stringtext ("AllPeopleSeemToNeedDataProcessing"); // 39 characters cout <"this sentence contains" <
            
             

     

    We can also use the + = symbol to add multiple characters to the string at a time.

    # Include
              
               
    # Include
               
                
    Usingnamespacestd; intmain () {stringfirstName ("Albert"); stringlastName ("Einstein"); stringfullName; // empty string fullName + = firstName; // Add the name to the empty string fullName + = ""; // Add a space fullName + = lastName; // Add the last name "cout" <"Your name" <
                
                 

     

    Run and output:

     

    Your name is Albert teinstein.

     

    Summary

    1. An array is a set of data elements of the same type in the memory.

      A static array is initialized as follows: int bestScore [5]; (contains 5 elements)

      The subscript of the first element in the array is 0 (for example, bestScore [0]).

      If the array size (number of elements) may change, you need to create a dynamic array using vector: vector Array (5 );

      We can create a multi-dimensional array, for example, int array [5] [6]; and a two-dimensional array with five rows and six columns is created.

      A string can be viewed as an array of characters. Each element is a character.

       

      Part 1 Lesson 10 advance notice

       

      Today's class is here. Come on!

      In the next lesson, we will learn:Reading and Writing files

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.