Fundamentals of C + + Grammar - learning notes

Introduction to programming

variable

Computer memory

Variable refers to the quantity that will change with the operation of the program.
Tips: for example, the quantity of coke and popcorn purchased by users at the vending machine are uncertain, and the final total price will be different, so these quantities and total prices exist in the computer in the form of variables. Maintaining these variables will use the storage function of the computer.

  • The storage function of the computer is realized by memory.
  • The operating system in the computer will generally divide the memory into different areas to store data for easy management.
  • Each basic storage unit in the memory can store one byte of data, and each byte has 8 bits, that is, 8 bits.
  • Each memory cell has a unique address, which is usually represented and distinguished by a hexadecimal number.

Declaration of variables

  • Variable declaration is the process of applying for variables from memory to store data. The general declaration method is data type variable name.
// Declare coke quantity variable
int coke;
// Declare popcorn quantity variable popcorn
int popcorn;
// Declare total consumption variable money
int money;

Naming rules for variables

Variable names, also known as identifiers, have fixed construction rules:

  • It can only be composed of words #, numbers and underscores;
  • The number cannot appear in the first position;
  • Keywords (reserved words) of C + + cannot be used as identifiers;
  • It is best to be simple and easy to understand, expressed in English or Pinyin with corresponding meaning;
  • In C + +, English letters in identifiers are case sensitive.

Initialization of variables

When declaring a variable, it can also be given an initial value, which is called variable initialization.

// Declare the total consumption variable money, and the initialization value is 0
int money = 0;

Output of variable

Use C + + code to display the initialized total consumption on the screen. This is called variable output. The output content is the value saved in the variable, not the variable name.

//Print the initialized total consumption on the screen and wrap it
cout << money << endl;
// Import the system input / output header file iostream
#include <iostream>

// Use standard namespace std
using namespace std;

int main() {
    // Declare coke quantity variable
    int coke;
    // Declare popcorn quantity variable popcorn
    int popcorn;
    // Declare the total consumption variable money, and the initialization value is 0
    int money = 0;
    
    // Print the initialized total consumption on the screen and wrap it
    cout << money << endl;
    
    return 0;
}

constant

Constant refers to the quantity that will not change with the program running. It is divided into two types: literal quantity and symbolic constant.

Literal

We call the data stored in variables literal.

The operation used to load literal quantity into variable is called assignment, which is generally written as variable name = literal quantity, such as:

// Xiao Dai needs two bottles of coke and three popcorn
coke = 2;       
popcorn = 3;

Literal quantity can be divided into the following types:

  • Whole number literal quantity: a number literal quantity without any decimal or exponential part, which is directly related to an integer in mathematics.
    Such as decimal 13, octal 0123 and hexadecimal 0x12a.

  • Floating point literal: a numeric literal in fractional or exponential form, which is directly related to decimals in mathematics.
    For example, 0.66 in decimal form and 1.23E-1 in exponential form.

  • Character literal quantity: divided into single character literal quantity and escape character literal quantity. For example, the letter 'a', line break '\ n', all characters are encoded in ASCII, with a total of 128 characters.

  • String literal: a sequence of characters enclosed in a pair of double quotes.
    Such as "Hello, World!".

symbolic constants

As the program operation does not change, after the name is given, there is a specific name called symbolic constant, which can be defined and initialized with const keyword (in C + + language, in order to use symbolic constant correctly, it must be initialized during definition):

const Data type constant name = Initial value;

perhaps

data type const Constant name = Initial value;

For example:

const int kCokePrice = 5;
int const kPopcornPrice = 10;

Note: the symbolic constant must be given an initial value when declared, and its value cannot be changed in the middle of the program. For example, the following statement is wrong:

const int a = 10;
a += 10;
const float PI;
PI = 3.1415926;

In C + + language, the number of bytes occupied by the string "C + +" in memory is: 4. At the end of each string, the system will automatically add an empty character '\ 0'.

Sequential structure programming

data type

  • In the variable declaration of C + +, the data type needs to be specified before the variable name.
Data type variable name;
  • The data type will determine what kind of information a variable stores, so as to determine the capacity of the variable and how much space needs to be allocated in memory.
  • The basic types of C + + include integer and floating-point numbers.

Numeric integer type

  • Numeric integers are used to represent numbers without decimal parts.
  • It can be divided into short, int, long and long long according to the size of memory occupied. The larger the memory occupied, the larger the range of values that can be represented.
short Type generally occupies 2 bytes
int Type generally takes up 4 bytes
long Type generally takes up 4 bytes
long long Type generally takes up 8 bytes
  • At the same time, it can be divided into signed version and unsigned version according to whether it represents negative value
    For example, unsigned int means unsigned int type. It can only represent positive value and the range is 0 ~ 2 32 − 1 0~2^{32}−1 0~232−1.
    Signed int represents the signed int type. It can represent negative value and the range is − 2 31 ~ 2 31 − 1 -2^{31}~2^{31} −1 −231~231−1.
    When you do not specify whether there is a symbol or not, it defaults to the signed version.

We can specify the data type of the variable during variable declaration or initialization according to the actual needs, for example:

short price = 500;    // Unit Price
int coupon = -2000;   // Discount
long total = 48000;   // Total price

Character integer type

  • Character type char is another special integer type, which is specially used to store the basic symbols in the computer: English letters, numbers, punctuation and so on.

  • The computer maps 128 characters to the corresponding numbers through ASCII coding, so we can represent all the characters in one byte (8 bits).

  • You can use either a character constant or an ASCII encoding corresponding to the character to assign a value to a variable of type char.

// Initializing a char type with a character constant
char size_1 = 'L';
// Initialize a char type with an integer constant, and the ASCII encoding value of character L is 76
char size_2 = 76;

Note: the character constant should be a single quotation mark, and the following assignment statement is wrong.

char size = "L";

Floating point type

  • Floating point numbers in C++ are divided into three types: float, double and long double, which represent different precision respectively.

  • The precision of the floating-point number and the range of its effective number of digits.
    Among the three floating-point types, larger memory space can represent more significant digits:
    The float type usually takes up 4 bytes and the significant bits are 6 bits
    The space occupied by double type is twice that of float type, that is, 8 bytes, and the significant digits are 15 bits
    The long double type generally takes up 16 bytes of space

You can specify the data type during floating-point variable declaration or initialization according to the actual needs, for example:

float ratio = 0.618;           // Golden ratio
double pi = 3.1415926;          // PI
long double atom = 1e80;   // Number of atoms in the universe
  • If there is int x; char y; short z; Then the data type of the value of expression (x - z) / (x + y) * 2.0 is double.
    When the operand is character or short shaping, the system automatically converts it to shaping. When the operand is real, the system will automatically convert to double precision. When the two operand types are different, the data type of the operand with low precision (or representing a small range) is transformed to the same type as the other operand for operation.

Arithmetic operators and expressions

Basic arithmetic and assignment operators

In C + +, the basic arithmetic operations are divided into the following five types: addition, subtraction, multiplication, division and modulo. C + + uses operator s to perform these arithmetic operations.

  • Addition: + operator, such as expression 3 + 2, can get 5
  • Subtraction: - operator, such as expression 21 - 12, the result is 9
  • Multiplication: * operator, such as expression 4 * 5, will get 20
  • Division: / operator, such as expressions 18 / 6 and 19 / 6, we get 3
  • Modulo:% operator, such as expression 32% 5, will get 2

For example, Xiaojian wants to buy 5 bags of biscuits and xiaodai wants to buy 3 bags of biscuits. When calculating the total number of bags of biscuits they need to buy, we will use the following statement:

int cookie;
cookie = 5 + 3;

The assignment operator =, which appears in the above calculation statement, represents the operation of assigning the value of the expression to the variable.

In practical use, many expressions contain multiple operators. For example, 5 + 3 * 6. C + + uses priority rules to decide which operator to use first.

  • For arithmetic operators, the usual algebraic priority is followed, with multiplication and division, modulus first and addition and subtraction second.
  • We can use () parenthesis pairs to specify the order of calculation, and the expression in () has the highest calculation priority.
  • For two operators with the same priority, the order of calculation will be determined by the combination law:
    The associative laws of arithmetic operators are from left to right;
    The associative law of assignment operators is from right to left.

Example:
Define variable int a; Then the expression a = 3, 5; After execution, the value of a and the value of the expression are 3 and 5 respectively.
First assign a to 3, then execute 5, and the value of the expression is 5.

Self increasing and self decreasing operator

The auto increment operator ++ acts on the variable operand to increment the value of the variable by 1:

  • When we use prefix mode, the variable will be incremented before the assignment operator, such as coffee_box = ++coffee
  • When we use suffix mode, the variable will be incremented after the assignment operator, such as coffee_box = coffee++

Self subtraction operator -- also works on variable operands, which can reduce the value of the variable by 1 on the original basis. The usage is the same as above.

Evaluate and assign operator

C + + provides an operator that combines arithmetic operation and assignment operation, which is called calculation and assignment operator. The symbol representation and function description are as follows:

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

int main() {
    int days;
    // After the calculation and purchase, the cookies are small enough to eat for a few days, and the value is assigned to the variable days
    days = (3 + 5) * 10 / 2;
    cout << days << endl;
    
    int coffee_box;
    int milk_box;
    int coffee = 0;
    int milk = 0;
    coffee_box = ++coffee;  //prefix pattern 
    milk_box = milk++;  //Suffix mode
    printf("coffee_box = %d, coffee = %d. \n", coffee_box, coffee);
    printf("milk_box = %d, milk = %d. \n", milk_box, milk);
    
    int beer_box;
    int wine_box;
    int beer = 1;
    int wine = 1;
    beer_box = --beer;  //prefix pattern 
    wine_box = wine--;  //Suffix mode
    printf("beer_box = %d, beer = %d. \n", beer_box, beer);
    printf("wine_box = %d, wine = %d. \n", wine_box, wine);
    
    int cake=10, nut=30, cheese=5, butter=4, flour=11;
    
    // Add three cakes
    cake += 3;
    // Reduce 12 nuts
    nut -= 12;
    // The cheese has tripled
    cheese *= 3;
    // Butter halved
    butter /= 2;
    // The flour is divided into 3 kilograms, each of which is packed. Finally, how much is left can't be packed
    flour %= 3;
    
    printf("cake = %d, nut = %d, cheese = %d, butter = %d, flour = %d. \n", cake, nut, cheese, butter, flour);
    
    return 0;
}

Operation results:

40
coffee_box = 1, coffee = 1. 
milk_box = 0, milk = 1. 
beer_box = 0, beer = 0. 
wine_box = 1, wine = 0. 
cake = 13, nut = 18, cheese = 15, butter = 2, flour = 2. 

Bitwise operators and expressions

Bit operation is an operation carried out under the binary representation of numerical value, so many unique operation rules will be involved. C + + contains six bitwise operators:

  • Bitwise and operator &, bitwise OR operator |, XOR operator^
    &, |, ^ are used to sum two binary operands bit by bit. Assuming that a and b are two operands that can only take binary values, i.e. 1 and 0, the following shows how these three operators work:


Let the variables A = 60 and B = 13 be taken as calculation examples. First, we convert them into eight bit binary numbers for representation, and get:

A = 0011 1100
B = 0000 1101

After calculation:

A & B = 0000 1100 // 12
A | B = 0011 1101 // 61
A ^ B = 0011 0001 // 49
  • Bitwise negation operator~

The negation operator ~, in C + +, calculates a single binary operand and performs negation operation according to each bit. The negation rule is 0 to 1 and 1 to 0.

Let variable A = 60 as an example of calculation:

A = 0011 1100
~A= 1100 0011 // -61
  • Shift left operator < < shift right operator > >

In C + +, the shift left operator < <, which can shift all the binary bits of an operand to the left by several bits, will get the result. The redundant binary bits on the left will be discarded, and the insufficient binary bits on the right will be supplemented by 0.

We apply the left shift operator to A = 60 for one shift, and we can get:

A = 0011 1100
A << 1 = 0111 1000

The shift right operator > > in C + + can shift all binary bits of an operand to the right by several bits, and the redundant bits on the right will be discarded, while the left is more complex:

  • For unsigned numbers, 0 will be added on the left;
  • For signed numbers, they will be supplemented with sign bits. Positive numbers are 0 and negative numbers are 1.

We apply the right shift operator to A = 60 for 2 shifts, and we can get:

A = 0011 1100
A >> 2 = 0000 1111
#include <iostream>
using namespace std;

int main() {
    int A = 60; // 0011 1100
    int B = 13; // 0000 1101
    
    cout << (A & B) << endl;
    cout << (A | B) << endl;
    cout << (A ^ B) << endl;
    cout << (~A) << endl;
    
    cout << (A << 1) << endl; // Shift left 1 bit
    cout << (A >> 2) << endl; // Shift right 2 bits
    
    return 0;
}

Operation results:

12
61
49
-61
120
15

oct is the output octal number.

int x = 040;
cout << oct << (x << 1);
//040 is an octal number, shifted one bit to the left, and output according to octal. The result is 100.

Loop structure programming

for loop

When you need to execute a piece of code many times, you can use the loop structure to solve the problem.

  • Loop structure refers to a program structure that needs to repeatedly execute a function in the program.
  • Judge whether to continue the function or exit the loop according to the conditions in the loop body.

The general form of the for loop statement can be expressed as follows:

for (Assign initial value to cyclic variable; Cycle conditions; Update loop variable) {
    Circulatory body
}

In addition to the normal loop, the loop control statement can change the normal sequence of program execution. break and continue are commonly used in loop control statements.

  • break
    It is usually placed in the loop body. When this sentence is executed, the whole loop will jump out, that is, the whole loop will be terminated immediately. (break statements can only be used in loop bodies and switch statement bodies)
  • continue
    It is usually placed in the loop body. When this statement is executed, it skips the current loop body and forces it to enter the next loop

give an example

  • Assume that from the 1st to the 100th day, you can deposit the same amount of money as the number of days every day, and output the whole number of deposits every day;
  • If the number of days is a multiple of 10 (days 10, 20, 30,...), you can neither save money nor output the total deposit on that day;
  • When the total deposit reaches 1000 yuan, it will not be deposited.
  • It can be written as follows:
// Enter an integer variable to represent the total deposit quantity
int savings = 0;

// The current number of days is represented by the circular variable i
// Start with 1
// Add 1 day after each cycle
// Jump out of the cycle if it is not satisfied for less than or equal to 100 days
for (int i=1; i<=100; i++) {
   // If the number of days is a multiple of 10, go directly to the next day
   if (i % 10 == 0)
       continue;
   
   // Total updated deposits
   savings = savings + i;
   // Total output deposits
   cout << i << ":total" << savings << endl;
   
   // When the deposit reaches 1000 yuan, it jumps out of the loop
   if (savings >= 1000)
       break;
}

Output leap year
Output all leap years since a certain year in the 21st century (the period from January 1, 2001 to December 31, 2100 is called the 21st century).

Note: the judgment condition of leap year is that the year of the year can be divided by 4, but can not be divided by 100, or can be divided by 400.

Enter Description:

Enter a certain cut-off year for the 21st century in one line.

Output Description:

Output all leap year years that meet the conditions line by line, that is, each year accounts for one line. If it is not the year of the 21st century, it will output "Invalid year!". If there is no leap year, output "None".

#include <iostream>
using namespace std; 

int main() {
    
    int end;
    bool is_leap_year,flag = false;
    cin >> end;
    if(end <= 2000 || end > 2100){
        cout << "Invalid year!" << endl;
        return 0;
    }

    for(int year=2001; year<=end; year++){
        is_leap_year = !(year%400)||(!(year%4)&&(year%100));
        if(is_leap_year){
            cout << year << endl;
            flag = true;
        }
    }

    if(!flag)
        cout << "None" <<endl;
    
    return 0;
}

Multiple cycles

Loop nesting is applicable to situations where there are repeated small operations in the large operations of the loop.

Circular nesting precautions:

  • It can be nested arbitrarily, such as for, for, while, while, while and while
  • If it is for embedded in for, the internal and external loop variables need to use different variables, otherwise it is easy to cause confusion
  • Indent to enhance code readability
  • It can be nested in multiple layers, but too many layers are easy to time out, which needs attention
    Print the 99 multiplication table by nesting the for loop inside the for loop:
// 1-9, print one line for each number
for (int i = 1; i <= 9; i++) {
    // In line i, for each number less than i, print an equation separated by tab
    for (int j = 1; j <= i ; j++) {
        cout << j << "*" << i << "=" << j*i << "\t";
    }
    // Line breaks are printed at the end of line i
    cout << endl;
}
  • Xiaoming grows apples

    Enter Description:

    Output Description:
Example 1:
Input:
4
4 74 -7 -12 -5
5 73 -8 -6 59 -4
5 76 -5 -10 60 -2
5 80 -6 -15 59 0
 Output:
222 1 0
#include<iostream>

using namespace std;
int a[1005][1005];
int b[1005] = {0};//Whether each tree has fruit drop statistics

int main() {
    int n;//How many trees are there
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i][0];//Several operations were performed
        for (int j = 1; j <= a[i][0]; j++) {
            cin >> a[i][j];
        }
    }
    int per_num = 0;//Apples per tree
    int sum_num = 0;//Last total remaining apples
    int dgcount = 0;//An apple tree with fallen fruit
    for (int i = 0; i < n; i++) {
        per_num = a[i][1];//Initial Apple situation
        for (int j = 2; j <= a[i][0]; j++) {
            if (a[i][j] < 0)//Fruit thinning
                per_num += a[i][j];
            else if (a[i][j] > 0) { //Statistics of fruit
                if (a[i][j] != per_num) {//In case of falling fruit, the statistics of the tree that has fallen fruit cannot be here, because a tree may be counted many times
                    b[i] = 1;
                }
                per_num = a[i][j];
            }
        }
        sum_num += per_num;
    }
    for (int i = 0; i < n; i++) {
        if (b[i]) {
            dgcount++;
        }
    }
    //Judge the number of groups that have lost fruit even three trees
    int e = 0;
    for (int i = 0; i <= n - 2; i++) {
        if (b[i] && b[i + 1] && b[i + 2]) {
            e++;
        }
    }
    if (b[n - 2] && b[n - 1] && b[0]) e++;
    if (b[n - 1] && b[0] && b[1]) e++;

    cout << sum_num << " " << dgcount << " " << e << endl;
    return 0;
}

array

One dimensional array

An array is an ordered collection of elements of the same type with a fixed size, which is used to store a series of data.

Array declaration

When declaring an array in C + +, we need to specify the type and number of elements. Among them, the number of elements must be a fixed constant, not a variable, so as to allocate a fixed space.

Element type array name[Array length];

Access to array elements

Each element of the array can be accessed through the index. The specific form is the array name [index serial number], such as sales[0], sales[1], sales[2]. The index sequence number of the array ranges from 0 to array length - 1.

Initialization of array

Arrays can be initialized in two ways:

One is to directly initialize the entire array while declaring:

Element type array name[Array length] = {Element 1, Element 2, ..., element n};
  • If the number of elements given in braces is less than or equal to the length of the array, these values will be assigned to all elements in turn, and the following defaults to 0
  • When initializing the entire array, you can omit the array length in brackets, so the default initialized array length is the number of elements in braces

Another initialization method is to access each element in the array after declaration, and initialize and assign values one by one.

Input and output of array

Ordinary arrays can only access a single element and input and output a single element.

give an example
Assuming that the sales volume of goods in the first month is 1, the sales volume of each subsequent month is the cumulative sales volume up to the previous month, that is to say:

  • The sales volume of the second month is the sales volume of the first month 1, and the total cumulative sales volume is 2
  • The sales volume of the third month is the cumulative sales volume of the first two months 2, and the total cumulative sales volume is 4
  • The sales volume of the fourth month is the cumulative sales volume of the first three months 4, and the total cumulative sales volume is 8
  • And so on

We want to calculate the cumulative sales volume of each month in a year and output it.

#include <iostream>
using namespace std;

int main() {
    // The initial value is assigned to the sales volume of the first month, and the rest are initialized to 0 by default
    int sales[12] = {1};

    // Calculate the cumulative sales volume of each month by cycle
    for (int i = 1; i < 12; i ++)
        sales[i] = 2 * sales[i-1];

    // Output 12-month cumulative sales
    for (int i = 0; i < 12; i ++)
        cout << sales[i] << " "; 
    
    return 0;
}
  • Find integer
This question requires input from N Find the given integer X. 
If found, output X The position of the first occurrence (counting from 1);
If not found, output“ Not Found". 

Enter Description:
The first line is a positive integer N(≤100),The second line gives N An integer.
The numbers shall not exceed long integers, separated by spaces, and an integer in the third line X

Output Description:
Output if found X Position, otherwise output“ Not Found". 

Example 1:
Input:
5
1 4 2 3 5
3
 Output:
4
#include <iostream>
using namespace std;

int main() {
    int n, x, idx;
    int nums[1001];
    bool flag = false;
    
    cin >> n;
    for (int i=0; i<n; i++)
        cin >> nums[i];
    cin >> x;
    
    for (int i=0; i<n; i++) {
        if (nums[i] == x) {
            flag = true;
            idx = i;
            break;
        }
    }
    
    if (flag)
        cout << idx+1 << endl;
    else
        cout << "Not Found" << endl;
    return 0;
}

Multidimensional array

We will introduce the usage of multidimensional array from four aspects: declaration, access to elements, initialization and input and output.

Declaration of multidimensional array

To declare a multidimensional array, you still need to specify the type of elements and the number of each dimension:

Element type array name[Length of the first dimension of the array][Length of the second dimension of the array]...[Array number n Dimension length]

Multidimensional array access element

Like one-dimensional arrays, multi-dimensional arrays still access elements through indexes. The access method is array name [first dimension index] [second dimension index] [index n].

Initialization of multidimensional array

There are two ways to initialize multidimensional arrays:

The first method is to initialize the entire multidimensional array when declaring. The initial values are placed in braces. If the number of elements given is less than its own number, the following will be initialized to 0 by default.

Suppose it is a two-dimensional array:

int scores[5][3] = {  
 {8, 4, 6},   /*  Initializes the row with index number 0 */
 {5, 6, 3},   /*  Initializes a row with index number 1 */
 {3, 2, 4},   /*  Initializes the line with index number 2 */
 {8, 7, 6},   /*  Initializes the line with index number 3 */
 {7, 9, 8}     /*  Initializes the line with index number 4 */
};

// Or omit the braces in the second layer
int scores[5][3] = {8, 4, 6, 5, 6, 3, 3, 2, 4, 8, 7, 6, 7, 9, 8};

The second initialization method is to access each element one by one after declaration, and initialize and assign values to each accessed element, which can be realized by nesting for statements.

Input and output of multidimensional array

Like one-dimensional arrays, ordinary multi-dimensional arrays can only input and output a single element.

give an example
Now there are five contestants and three judges have scored them in the two rounds of competition, as shown in the figure below.

Suppose that the small key finds that the score of the second round of judge 1 on player 1 is wrong, and wants to correct it to the re-entered score. After correction, the score of each judge on each player will be output, and the total score of each player will be calculated and output. The total score is calculated as the sum of the average scores of the two rounds (rounded down).

At this time, we can use three-dimensional array to describe the data structure and simulate the above process.

// Declare and initialize score
int scores[5][3][2] = {
    {{8, 7}, {4, 3}, {6, 5}},
    {{5, 6}, {6, 5}, {3, 8}},
    {{3, 8}, {2, 9}, {4, 7}},
    {{8, 7}, {7, 5}, {6, 3}},
    {{7, 7}, {9, 7}, {8, 9}}
};

int avg_score, score_sum;

// Correction score
scanf("%i", &scores[0][0][1]);

for (int i=0; i<5; i++) {
    score_sum = 0;
    cout << "player" << (i+1);
    
    // Print the score for each round of the player and count the average score
    for (int k=0; k<2; k++){
        cout << "The first" << (k+1) << "Round score:";
        avg_score = 0;
        
        // Calculate the average score of the player in the round
        for (int j=0; j<3; j++) {
            avg_score += scores[i][j][k];
            cout << scores[i][j][k] << " ";
        }
        cout << endl;
        avg_score /= 3;
        
        // The total score of the player plus the average score of the round
        score_sum += avg_score;
    }
    
    cout << score_sum << endl;
}
  • Row column interchange
Enter a n*m For large and small matrices, exchange their rows and columns, replace the first row with the first column, replace the second row with the second column, and so on.

1 <= n, m <= 100

Enter Description:
Two integers in the first line n,m
 next n Line, each line m Integer

Output Description:
m Line, each line n An integer representing the matrix after exchange.

Example 1:
Input:
2 3
1 2 3
4 5 6
 Output:
1 4
2 5
3 6

#include <iostream>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    int nums[m][n];
    
    for (int i=0; i<n; i++)
        for (int j=0; j<m; j++)
            cin >> nums[j][i];
    
    for (int i=0; i<m; i++) {
        for (int j=0; j<n; j++)
            cout << nums[i][j] << " ";
        cout << endl;
    }
    return 0;
}

character string

Character array

Character array is an array composed of several character elements. It can declare, initialize, access elements and input and output elements one by one in the way of ordinary array.

In most cases, character arrays are used to store strings. This kind of string stored in character arrays is called character array string.

Character array type string is actually a one-dimensional array terminated with character \ 0. The type of elements in the array is character type. The basic operations of character array type string are as follows:

  • Declaration: it is the same as the normal character array, but because a \ 0 needs to be added, the length of the character array needs to be 1 more than the number of characters in the string.

  • Access element: accessed by index.

  • Initialization: there are two ways to initialize character array strings
    The first initialization method is the same as the ordinary character array. Each element is assigned an initialization value, but the character '\ 0' needs to be added
    The second way is to initialize the character array with a string constant

// The first one: assign initialization value to each element
char userName[11] = {'L', 'a', 'o', 'W', 'a', 'n', 'g', '\0'};
char userName[11] = {'L', 'a', 'o', 'W', 'a', 'n', 'g'};
char userName[] = {'L', 'a', 'o', 'W', 'a', 'n', 'g', '\0'};

//The second is to initialize the character array with string constants
char userName[11] = {"LaoWang"};
char userName[11] = "LaoWang";
  • Input and output: in addition to inputting and outputting each element one by one like an ordinary array, character array strings can also be input and output directly
char userName[11];

scanf("%s", userName);
printf("%s", userName);

cin >> userName;
cout << userName <<endl;

Since string is a common type, some common string processing functions are officially provided:

  • strcat(s1, s2) connection string
  • strlen(s1) get string length
  • strcmp(s1, s2) compares the dictionary order of strings
  • strcpy(s1, s2) copy string

give an example:

#include <iostream>
// In order to call these functions, we must add it to the header file cstring
#include <cstring>
using namespace std;

int main() {
    char userName_old[10] = "LaoWang";
    char userName_new[10] = "Liu";

    // Use strcat: return userName_new received username_ String after old
    cout << strcat(userName_old, userName_new) << endl;

    // Return username_ Length of old
    cout << strlen(userName_old) << endl;

    // Returns the comparison of new and old user name dictionaries
    cout << strcmp("LaoWang", "Liu") << endl;

    //Copy "Liu" to userName_old
    strcpy(userName_old, "Liu");
    cout << userName_old << endl;
    // Because only the first four elements have been modified, the fifth element is still 'a'
    cout << userName_old[4] << endl;
    
    return 0;
}

string type

C + + provides a better set of tools, called Standard Template Library (STL), which encapsulates many functions, such as some data structures (queues, etc.) and algorithms (sorting, etc.), of which a data type called string can be specially used to deal with problems related to character strings.

The string type directly treats the string as a whole and can be used like integer variables and character variables.

The usage of string type has the following precautions:

  • Header file
    First, you need to load the header file where the string type is located.
# include <string>
  • Declaration and initialization
    The declaration and initialization of string type are the same as ordinary variables.
// statement
string a;

// Declaration and initialization
string b = "yes";
  • Input and output
    string type strings are generally input and output directly through cin and cout.

Since string is a common type, the official provides some common processing functions of character array strings. It is easier to use string type to complete the operation between these strings:

s1 + s2 Connection string
s1.size() perhaps s1.length() Get string length
strcmp(s1, s2) Compare the dictionary order of strings
s1 = s2 Copy string

give an example

Let's try some operations on the new and old user names of Xiaoliu:

string userName_old = "LaoWang";
string userName_new = "Liu";
string str;
int len;

// Connect the new and old user names of Xiaoliu and assign them to str
str = userName_old + userName_new;
cout << userName_old << " + " << userName_new << " = " << str << endl;

// Total length of str after output connection
cout << "str length:  " << str.size() << endl;
cout << "str length:  " << str.length() << endl;

// Compare dictionary order of new and old user names
cout << (userName_old > userName_new) << endl;

// Then assign the old user name to str
str = userName_old;
cout << "str : " << str << endl;

In addition, there are other very convenient operation functions of string type. See the following table for details:


  • Reverse word order
Input a sentence composed of three words and output the three words in reverse, such as input you love i,Then output i love you,The length of each word is no more than 100 (please use string Type Implementation)

Enter Description:
One line, three strings, separated by spaces

Output Description:
One line, reverse the order of the three strings, separated by spaces

Example 1:
Input:
you love i
 Output:
i love you
# include <iostream>
# include <string>

using namespace std;

int main() {
    string words[3];
    for (int i=0; i<3; i++)
        cin >> words[i];
    
    cout << words[2] << " " << words[1] << " " << words[0];
    
    return 0;
}

Functions and structures

Since an array can only store a set of information of the same data type, we can use a structure to aggregate a set of different types of data into a whole, so as to facilitate the processing of this information. The space occupied by a structure is the sum of the memory capacity required by each member of the structure.

  • Definition of structure
    In addition to the name of each structure, there are many different types of member variables used to represent the properties of the structure. The structure is defined as follows:
struct Structure name {
    Data type 1 variable name 1;
    Data type 2 variable name 2, Variable name 3;
    ...
    data type n Variable name m;
};
  • Structure variable declaration
    Structure variables are declared in a similar way to normal variables. For the defined structure Student, the variables declaring the structure type are as follows:
struct Student{    
    int number, birth_year;
    string name;
};

// Declare three students
Student zhang_san, li_si, wang_mazi;

You can also declare an array of structural variables to hold the information of 500 students.

// Declare an array of students. The length of the array is 500. You can save the information of 500 students
Student students[500];
  • Initializing a struct for a struct variable, we can initialize it in two ways: using an initialization list or a constructor.

Using the initialization list is similar to the initialization of array. Each member in the structure will be initialized according to the given elements. If the given elements are less than the number of members, the last one will remain uninitialized. for instance:

struct Student{    
    int number, birth_year;
    string name;
};

// Initialize a student named Zhang San who was born in 12000
Student zhang_san = {1, 2000, "ZhangSan"};

Constructor initialization, which can provide default values when creating a structure variable without passing the values of some member variables. We can first complete a constructor inside the structure, and then call this constructor to initialize the structure variable:

struct Student{    
    int number, birth_year;
    string name;
    
    // Define constructor in structure
    // At initialization, the year of birth of all students is set to 2000
    // Two parameters can be passed in, representing the student number and name respectively. If no parameter is passed in, the default student number is 0 and the name is ""
    Student (int num=0, string n="") {
        number = num;
        birth_year = 2000;
        name = n;
    }
};

// Only two parameters can be passed during initialization
Student li_si(2, "LiSi");
  • Structure member access
    If you want to access a member of a structure variable, you can use the structure variable name Structure member variable names can be accessed by:
cout << zhang_san.number << endl;
cout << zhang_san.name << endl;
cout << li_si.birth_year << endl;
  • code:
  • Storage of employee information
We now need to create a structure of the company's employees`Employee`,be used for

- Save the employee's number, name and required working hours per day (8 hours by default)
- Initialize small one (No. 1), XiaoYi),Sophomore (No. 2), XiaoEr),Small six (No. 3), XiaoLiu),Xiao Si (No. 4), XiaoSi),Small five (5), XiaoWu)Information about these five employees
- Write a function to display employee information

We can do this:

#include <iostream>
using namespace std;

// Define the structure Employee and declare the structure array employees with a length of 5_ info
struct Employee{    
    int number, working_hours;
    string name;
    
    // Build function
    Employee (int num=0, string n="") {
        number = num;
        working_hours = 8;
        name = n;
    }
} employees_info[5];

// A function that displays information about an employee
void showEmployee(const Employee &employee_info) {
    cout << "Employee Number : " << employee_info.number << endl;
    cout << "Name : " << employee_info.name << endl;
    cout << "Working Hours : " << employee_info.working_hours << endl;
}

int main() {
    // Initialize 5 employees
    employees_info[0] = Employee(1, "XiaoYi");
    employees_info[1] = Employee(2, "XiaoEr");
    employees_info[2] = Employee(3, "XiaoLiu");
    employees_info[3] = Employee(4, "XiaoSi");
    employees_info[4] = Employee(5, "XiaoWu");
    
    // Call the function to display 5-bit information
    for(int i=0; i<5; i++) {
        showEmployee(employees_info[i]);
    }
    return 0;
}
  • Oldest student
input n The information of students, including name, gender and age, and then output the information of the oldest student. (ensure that the maximum age is not repeated)

1 <= n <= 10
 Name length is less than or equal to 20
 Gender M or F

Enter Description:
The first line is an integer n
 next n Line, followed by the student's name, gender and age.

Output Description:
One line, followed by name, gender and age, separated by a space.

Example 1:
Input:
2
Kal'tsit F 1000
Amiya F 14
 Output:
Kal'tsit F 1000
#include 
<iostream>
#include <string>

using namespace std;

struct Student {
    string name;
    char gender;
    int age;
};

int main() {
    int num, max_age, max_age_idx;
    cin >> num;
    
    string n;
    char g;
    int a;
    
    Student students[11];
    for (int i=0; i<num; i++) {
        cin >> n >> g >> a;
        students[i] = {n, g, a};
    }
    
    max_age = 0;
    max_age_idx = 0;
    for (int i=0; i<num; i++) {
        if (students[i].age > max_age) {
            max_age = students[i].age;
            max_age_idx = i;
        }
    }
    cout << students[max_age_idx].name << " " << students[max_age_idx].gender << " " << students[max_age_idx].age;
    
    return 0;
}

learning resource

Qingzhou Zhixue: https://www.qingzhouzhixue.com/

Tags: C++

Posted by TanyaTR on Sat, 16 Apr 2022 02:38:02 +0930