Summary of C + + class topics

1. Description

Analyze the custom class mysrtcla given below, the main function given later and the screen display results after the execution of the program. Then, the specific implementation of its three member functions (used to complete the set user-defined functions) is given (supplemented) outside the class, so that the screen display result after program execution is:

abcdedcba 

True

The program code of class definition and main function part is as follows:

class myStrCla {  

//Custom class myStrCla

    char str[101];  

/ / store the string (assuming that the string does not exceed 100 characters)

    int len; 

/ / the specific length of the current string

public: 

    myStrCla(char* s) ; 

/ / constructor. s brings the initial value of string str

    void strOut();   

/ / screen output string str

    bool strIsPal(); 

/ / whether the str string is a palindrome string (the same string for forward reading and reverse reading)

};

input

Input a total of one line, enter a string, no more than 100 characters

output

There are two lines of output. The first part is to call the strOut() function of myStrCla class to output the string STR, and the second part is to call the strIsPal() function of myStrCla class to judge whether the str string is a "palindrome string" and output False or True

sample input

abcdedcba

sample output

abcdedcba

True

#include <iostream> 
using namespace std;

class myStrCla { 
 //Custom class myStrCla 
    char str[101];
//Store string (assuming that the string does not exceed 100 characters)
    int len;  
 //The specific length of the current string 
public: 
    myStrCla(char* s) {
        len = 0;
        while (*(s + len) != '\0') {
            str[len] = *(s + len);
            len += 1;
        }
    }
//Constructor. s brings the initial value of the string str
    void strOut() {
        for (int i = 0; i < len; i++) {
            cout << str[i];
        }
        cout <<endl;
    }
//Screen output string str
    bool strIsPal() {
        int first = 0, last = len - 1;
        while (last >= first) {
            if (str[last] != str[first]) {
                return false;
            }
            last--;
            first++;
        }
        return true;
    } 
    //Whether str string is "palindrome string" (the same string for forward reading and reverse reading)
};

int main() {
    char s[101];
    cin >> s;
    myStrCla obj1(s);
    obj1.strOut();
    if (obj1.strIsPal())
        cout << "True" << endl;
    else
        cout << "False" << endl;
}

2. Description

Design a student class (CStudent), which has private data members: registration number, name, mathematics, foreign language and computer course grades.

The public member functions with are: sum, the function of finding the total score of three courses; Find the function average of the average score of three courses; Function display for displaying student data information; Set the function setData of student data information.  

Then, through the main function, input the array of student objects (student information of the whole class) from the keyboard, then calculate the total score and average score of each student, and display all the data information of the student with the highest total score in the whole class.

Class functions are defined as follows:

class CStudent { 

/ / student class CStudent

     unsigned long reg_num;  

/ / data member: registration number

     char *name; (or string name)

/ / data member: name

    float math, eng, comp; 

/ / data members: math, English, computer scores

public: 

     float sum();

/ / find the function sum of the total score of three courses

     float average(); 

/ / find the function average of the average scores of the three courses

    void display();

/ / display function for displaying student data information

    void setData(unsigned long r, char* n, float m, float e, float c);

/ / set the function setData of student data information

};

input

In the first line, enter a number n (1 < = n < = 150), and then enter n lines. Each line includes a member's registration number, name, math score, English score and computer score;

output

The output has n+1 lines, and the first n lines output the total score and average score of each member in order; The last line calls the display() function to output the registration number, name, math score, English score and computer score of the member with the highest average score (if the highest average score is the same, the student with the highest average score for the first time will be output)

sample input

3

100001 ma 78 86 90

100002 li 85 91 88

100003 hu 82 89 88

sample output

254 84.6667

264 88

259 86.3333

100002 li 85 91 88

#include<iostream>
using namespace std;

class CStudent { 
    unsigned long reg_num;  
    char *name;  
    float math, eng, comp; 
public: 
     float sum(); 
    float average(); 
    void display();
    void setData(unsigned long r, char* n, float m, float e, float c);

};

float CStudent::sum() {
    return this->math+this->eng+this->comp;
}
float CStudent::average() {
 return (this->math + this->eng + this->comp)/3;
}
void CStudent::display() {
    cout << this->reg_num << " " << this->name << " " << this->math << " " << this->eng << " " << this->comp << endl;
}
void CStudent::setData(unsigned long r, char* n, float m, float e, float c) {
    this->reg_num = r;
    this->name = n;
    this->math = m;
    this->eng = e;
    this->comp = c;
}

int main() {
    CStudent stu[150];
    unsigned long r;
    float m;
    float e;
    float c;
    int n;
    const char *name;
    cin >> n;
    for (int i = 0; i < n; i++) {
        name = new char();
        cin>>r>>(char*)name>>m>>e>>c;
        stu[i].setData(r,(char*)name, m, e, c);
    }
    int max = -1;
    int max_index = 0;
    for (int i = 0; i < n; i++) {
    cout << stu[i].sum() << " " << stu[i].average() << endl;
            if (max < stu[i].sum()) {
                max = stu[i].sum();
                max_index = i;
            }
    }
    stu[max_index].display();
}

3. Description

Queue is a data structure commonly used in programming. Its structure is similar to stack, but the data in the queue is first in first out. Follow the definition of stack and customize a queue class queue. The batch of data of the same type that needs to be saved and processed in the queue is stored in an array of maxsize.

Class functions are defined as follows:

const int max_size = 10;

class queue {

private:

    float data[max_size]; 

/ / store the actual data of the queue in data. maxsize is a well-known constant defined in advance

    int front, rear; 

/ / initial and final subscripts. The queue data is placed in data[front+1] to data[rear]

      int num;

public:

    queue(void); 

/ / constructor, set front=rear=-1, num=0, which means the queue is empty

    bool Empty(void); 

/ / judge whether the queue is empty (that is, judge whether num is 0)

    bool Full(void); 

/ / judge whether the queue is full (that is, judge whether num is equal to maxsize)

    void Add(float); 

/ / add data to the end of the queue (add to data[rear+1], num increases by 1)

    float Delete(void);

};

input

Enter a number N in the first line, and then enter n lines. Each line has four types:

1. Entering 0 + space + a floating-point number a means adding a number a to the queue

2. Entering 1 means to delete a number from the queue and output it

3. Entering 2 means that you need to call the function whether the queue is empty and output whether the queue is empty. If it is empty, it is 1 and if not, it is 0

4. Input 3 means you need to call the queue full function and output whether the queue is full. If it is full, output 1 and if it is not full, output 0

output

See input description

sample input

10

0 3

0 4

0 5

0 8

3

2

1

0 9

1

1

sample output

0

0

3

4

5

#include<iostream>
using namespace std;

const int max_size = 10;
class queue {
private:
    float data[max_size];
 //The actual data of the queue is stored in data, and maxsize is a well-known constant defined in advance 
    int front, rear; 
    //The head and tail subscripts, and the queue data are placed in data[front+1] to data[rear] 
    int num;
public:
    queue(void); 
    //Constructor, set front=rear=-1, num=0, which means that the queue is empty 
    bool Empty(void); 
//Judge whether the queue is empty (that is, judge whether num is 0) 
    bool Full(void); 
//Judge whether the queue is full (that is, judge whether num is equal to maxsize) 
    void Add(float); 
//Add data to the end of the queue (add to data[rear+1], num increases by 1)
    float Delete(void);
};

queue::queue(void) {
    num = 0;
    front = rear = -1;
}

bool queue::Empty() {
    if (num == 0) {
        return true;
    }
    else {
        return false;
    }
}

bool queue::Full() {
    if (num == max_size) {
        return true;
    }
    else {
        return false;
    }
}

void queue::Add(float a) {
    num += 1;
    rear =(rear+1)%max_size;
    data[rear] = a;
}

float queue::Delete() {
    num -= 1;
    front = (front + 1) % max_size;
    return data[front];
}

int main() {
    queue q;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        int op;
        cin >> op;
        if (op == 0) {
            float a;
            cin >> a;
            q.Add(a);
        }
        else if (op == 1) {
            cout << q.Delete() << endl;
        }
        else if (op == 2) {
            cout << q.Empty() << endl;
        }
        else if (op == 3) {
            cout << q.Full()<<endl;
        }
    }
}

4. Description

Define a two-dimensional square matrix class matrix. By overloading binary operators "+", "-", "*" and unary operator "~", matrix addition, matrix subtraction, matrix multiplication and matrix transpose are realized.  

The Matrix class is defined as follows:

class matrix {

public:

    int r, c; 

/ / r row c column matrix

    int** mem; 

/ / matrix data

    matrix(int a,int b); 

/ / two parameter constructor, which allocates mem dynamic array of row a and column b to store data

    ~matrix(); 

/ / destructor to release mem dynamic array

    matrix operator+ (matrix & m); / / matrix addition

    matrix operator- (matrix & m); / / matrix subtraction

    matrix operator* (matrix & m); / / matrix multiplication

    matrix operator~ (); / / matrix transpose

    void display(); / / output matrix

};

input

There are three rows in total. The first row inputs four positive integers r1, c1, r2 and c2, representing row r1 and column c1 of matrix x and row r2 and column c2 of matrix y respectively. r1, c1, r2 and c2 are greater than 0.

output

The output has four parts, one line should be left blank between each part, and the last line should not be left blank; The four parts output the results of X + y, X-Y, X * y and ~ x respectively; If the two matrices cannot be added, subtracted or multiplied, "err" is output in the corresponding part

sample input

2 3 3 2

1 2 3 4 5 6

1 2 3 -1 0 1

sample output

err

err

7 3

19 9

1 4

2 5

3 6

#include <iostream>
using namespace std;

class matrix {
public:
    int r, c; 
    //Matrix of row r and column c
    int** mem; 
    //Matrix data
    matrix(int a,int b); 
    //The two parameter constructor allocates the mem dynamic array of row a and column b to store data
    ~matrix(); 
    //Destructor to release mem dynamic array

    matrix operator+ (matrix & m); //Matrix addition
    matrix operator- (matrix & m); //Matrix subtraction
    matrix operator* (matrix & m); //Matrix multiplication
    matrix operator~ (); //Matrix transpose
    void display(); //Output matrix
};

matrix::matrix(int a, int b) {
    r = a;
    c = b;
    if(r ==0 || c==0){
        mem = NULL;
    } else {
        mem = new int*[r];
        for(int i=0;i<r;i++){
            mem[i] = new int[c];
        }
    }
}

matrix::~matrix() {
    if(mem != NULL) {
        for(int i=0;i<r;i++){
            delete[] mem[i];
        }
        delete[] mem;
    }
}

matrix matrix::operator+(matrix &m) {
    matrix res(r,c);
    if(r!=m.r || c!=m.c){
        matrix tmp(0,0);
        res = tmp;
    }else {
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                res.mem[i][j] = mem[i][j] + m.mem[i][j];
            }
        }
    }
    return res;
}

matrix matrix::operator-(matrix &m) {
    matrix res(r,c);
    if(r!=m.r || c!=m.c){
        matrix tmp(0,0);
        res = tmp;
    } else {
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                res.mem[i][j] = mem[i][j] - m.mem[i][j];
            }
        }
    }
    return res;
}

matrix matrix::operator*(matrix &m) {
// If two matrices cannot be multiplied
    matrix res(r,m.c);
    if(c != m.r){
        matrix tmp(0,0);
        res = tmp;
    } else {
        for(int i=0;i<r;i++){
            for(int j=0;j<m.c;j++){
                int tmp =0;
                for(int x=0;x<c;x++){
                    tmp = tmp + mem[i][x] * m.mem[x][j];
                }
                res.mem[i][j] = tmp;
            }
        }
    }
    return res;
}

matrix matrix::operator~() {
    matrix res(c,r);
    for(int i=0;i<c;i++){
        for(int j=0;j<r;j++){
            res.mem[i][j] = mem[j][i];
        }
    }
    return res;
}

void matrix::display() {
    if(r==0){
        cout << "err" << endl;
    }
    for(int i=0;i<r;i++){
        for(int j=0;j<c-1;j++){
            cout << mem[i][j] << " ";
        }
        cout << mem[i][c-1] << endl;
    }
}

int main() {
    int r1,c1,r2,c2;
    cin >> r1 >> c1 >> r2 >> c2;

// Create matrix object
    matrix x(r1,c1);
    matrix y(r2,c2);

// Read matrix data
    for(int i=0;i<r1;i++){
        for(int j=0;j<c1;j++){
            cin >> x.mem[i][j];
        }
    }

    for(int i=0;i<r2;i++){
        for(int j=0;j<c2;j++){
            cin >> y.mem[i][j];
        }
    }

    (x+y).display();
    cout << endl;
    (x-y).display();
    cout << endl;
    (x*y).display();
    cout <<endl;
    (~x).display();

    return 0;
}

5. Description

Design a suffix simple one-step calculator class MyCalcu1, which has the following functions:

(1) Read the suffix formula str (a string) from the keyboard, create a new object cal through a one parameter constructor, and set the formula str.  

(2) It can perform addition, subtraction, multiplication and division, and the operation object is real data.  

(3) The operator has no priority, that is, it is always executed in the form of "suffix simple single step". For example, "9 3 - 4 *", it means that the operation objects 9 and 3 are subtracted by the suffix to obtain the result 6, and then 6 and the subsequent 4 are multiplied by the suffix to obtain the result 24. If the equal sign is encountered later, the result 24 is output to end the processing.

(4) It has a certain error elimination function. When the user inputs an incorrect formula, it outputs "err".

The class MyCalcu1 is defined as follows:

class MyCalcu1{

public:

    string expression; 

/ / suffix expression

    MyCalcu1(string exp);

    void process(); 

/ / internally calculate and output the result of suffix expression

};

input

Enter a line str to indicate the suffix expression to be evaluated. Numbers and symbols are separated by spaces

output

Output the result of suffix expression calculation. If the expression is wrong, output "err"

sample input

12.3 5 / 8.1 + 1.5 *

sample output

15.84

Tips

1. It is necessary to judge whether the number is a real number: for example:. 01 1.0 - 1.0 + 1 are all correct real numbers, + - 1- 1 -0.9. 1 + + 1 are all wrong real numbers.

2. You need to judge whether the expression can be calculated, and only need to support + - * / at the same time. Other operators output "err".

3. You need to implement the member method process of the class, then instantiate MyCalcu1 in the main function, and call this method to calculate the suffix expression.

#include <iostream>
#include <stack>
#include <vector>
using namespace std;

class MyCalcu1{
public:
    string expression; 
    MyCalcu1(string exp);
    void process(); 
};

MyCalcu1::MyCalcu1(string exp) {
    expression = exp;
}

// Determine whether it is a normal real number
bool isNumber(string s) {
    bool sign = 0;
    bool num = 0;
    bool dec = 0;
    int point = 0;

    int n = s.size();
    for (int i = 0; i < n; ++i) {
        if (s[i] == '+' || s[i] == '-') {
//Two symbols cannot appear
            if (sign) {
                return false;
            }
//If the symbol bit is at the beginning
            if (i == 0) {
                sign = 1;
            }
//Symbols cannot appear elsewhere
            else {
                return false;
            }
        }
        else if (s[i] == '.') {
//Only one point can exist
            if (point) {
                return false;
            }
            point = 1;
        }
        else if (s[i] >= '0' && s[i] <= '9') {
//If there is a decimal point, the current number is the decimal place, and the decimal place is valid
            if (point) {
                dec = 1;
            }
//Otherwise, it is an integer bit, and the integer bit is valid
            else {
                num = 1;
            }
        }
        else {
//Other characters are returned directly
            return false;
        }
    }
//Returns whether it constitutes a valid integer or decimal
    return num || dec;
}

void MyCalcu1::process() {
    stack<double> stack;
    vector<string> vec;

// Split expressions by spaces
    string tmp = "";
    int exp_size = expression.size();
    for(int i=0;i<exp_size;i++){
        if(expression[i]!=' '){
            tmp += expression[i];
        } else {
            vec.push_back(tmp);
            tmp = "";
        }
    }
    vec.push_back(tmp);

// Start calculation
    int vec_size = vec.size();
    for(int i=0;i<vec_size;i++){
        string str = vec[i];

// Is the number put directly into the stack
        if(isNumber(str)){
            stack.push(stod(str));
        }
// Is it an operator
        else if(str=="+" || str == "-" || str == "*" || str == "/"){
// Failure to get a number for calculation indicates an error in the expression
            if(stack.size()<2) {
                cout << "err" << endl;
                return;
            }

            double b = stack.top();
            stack.pop();
            double a = stack.top();
            stack.pop();

            if(str == "+"){
                a+=b;
            } else if(str == "-"){
                a-=b;
            } else if(str == "*"){
                a*=b;
            } else if(str == "/"){
                a/=b;
            }
            stack.push(a);
        }
// Another character error occurred
        else {
            cout << "err" << endl;
            return;
        }
    }

    if(stack.size()==1){
        cout << stack.top() << endl;
    } else {
        cout << "err" << endl;
    }
}

int main() {
    string exp;
    getline(cin,exp);
    MyCalcu1 cal(exp);

    cal.process();

    return 0;
}

6. Description

Design a simple calculator class MyCalcu2, which has the following functions:

(1) Read the infix formula str (a string) from the keyboard, create a new object cal through a one parameter constructor, and set the formula str.

(2) You can add, subtract, multiply and divide. The operation object is real data. In case of an equal sign, the calculation ends and the result is displayed.

(3) Operations should have priority, and multiplication and division take precedence over addition and subtraction.

(4) It has a certain error elimination function. When the user inputs an incorrect formula, it outputs "err".

Class MyCalcu2 is defined as follows:

class MyCalcu2{

public:

    string expression;

/ / infix expression

    MyCalcu2(string exp);

    void process(); 

/ / internally calculate and output the calculation result of infix expression

};

input

Enter a line str to represent the infix expression to be evaluated. Numbers and symbols are separated by spaces

output

Output the result of infix expression calculation. If the expression is wrong, output "err"

sample input

12.5 - 2.2 * 5 / 3 + 1.3 * 2

sample output

11.4333

Tips

1. Implement the method process of class to realize the calculation function

2. Infix expression can be converted to suffix expression for calculation. Priority needs to be considered in the conversion process

#include <iostream>
#include <stack>
#include <vector>
using namespace std;

class MyCalcu2{
public:
    string expression;
    MyCalcu2(string exp);
    void process();
};

MyCalcu2::MyCalcu2(string exp) {
    expression = exp;
}

// Gets the priority of the calculated symbol
int getPriority(string ch)
{
    int res =0;
    if(ch == "+" || ch == "-"){
        res = 1;
    } else if(ch == "*" || ch =="/"){
        res = 2;
    }
    return res;
}

// Determine whether it is a normal real number
bool isNumber(string s) {
    bool sign = 0;
    bool num = 0;
    bool dec = 0;
    int point = 0;

    int n = s.size();
    for (int i = 0; i < n; ++i) {
        if (s[i] == '+' || s[i] == '-') {
//Two symbols cannot appear
            if (sign) {
                return false;
            }
//If the symbol bit is at the beginning
            if (i == 0) {
                sign = 1;
            }
//Symbols cannot appear elsewhere
            else {
                return false;
            }
        }
        else if (s[i] == '.') {
//Only one point can exist
            if (point) {
                return false;
            }
            point = 1;
        }
        else if (s[i] >= '0' && s[i] <= '9') {
//If there is a decimal point, the current number is the decimal place, and the decimal place is valid
            if (point) {
                dec = 1;
            }
//Otherwise, it is an integer bit, and the integer bit is valid
            else {
                num = 1;
            }
        }
        else {
//Other characters are returned directly
            return false;
        }
    }
//Returns whether it constitutes a valid integer or decimal
    return num || dec;
}

void MyCalcu2::process() {
    stack<string> sign;
    stack<double> stack;
    vector<string> vec;

// Convert the expression of infix into suffix and put it into vec
    string tmp = "";
    int exp_size = expression.size();
    for(int i=0;i<exp_size;i++){
        if(expression[i]!=' '){
            tmp += expression[i];
        }

// If it's a space or the last part
        if(expression[i]==' ' || i==exp_size-1)
        {
// Is the number put directly into vec
            if(isNumber(tmp)){
                vec.push_back(tmp);
            }
// Is a calculation symbol
            else if(tmp == "+" || tmp == "-" || tmp == "*" || tmp == "/"){
// Pop the low priority ones out of the stack
                while(!sign.empty() && getPriority(sign.top())>=getPriority(tmp)){
                    vec.push_back(sign.top());
                    sign.pop();
                }
                sign.push(tmp);
            }
// An error character occurred
            else {
                cout << "err" << endl;
                return;
            }
            tmp = "";
        }
    }

// Finally, put the remaining symbols in sign into vec
    while(!sign.empty()){
        vec.push_back(sign.top());
        sign.pop();
    }

// Start calculation
    int vec_size = vec.size();
    for(int i=0;i<vec_size;i++){
        string str = vec[i];

// Is the number put directly into the stack
        if(isNumber(str)){
            stack.push(stod(str));
        }
// Is it an operator
        else if(str=="+" || str == "-" || str == "*" || str == "/"){
// Failure to get a number for calculation indicates an error in the expression
            if(stack.size()<2) {
                cout << "err" << endl;
                return;
            }

            double b = stack.top();
            stack.pop();
            double a = stack.top();
            stack.pop();

            if(str == "+"){
                a+=b;
            } else if(str == "-"){
                a-=b;
            } else if(str == "*"){
                a*=b;
            } else if(str == "/"){
                a/=b;
            }
            stack.push(a);
        }
// Another character error occurred
        else {
            cout << "err" << endl;
            return;
        }
    }

    if(stack.size()==1){
        cout << stack.top() << endl;
    } else {
        cout << "err" << endl;
    }
}

int main() {
    string exp;
    getline(cin,exp);
    MyCalcu2 cal(exp);

    cal.process();
    return 0;
}

Keywords: C++

Added by VinzC on Sat, 11 Dec 2021 16:27:02 +0200