C + + language -- implementation of sequence table, using the method of dynamic array

Keywords: C++

Some common things in C + +, through the use of dynamic array to achieve the order table,

Have mastered the following knowledge points:

1. There are three methods of pretreatment

Macro definition, file inclusion, conditional compilation

2. When using a variable with the same name, you can use the namespace class in the outer layer to solve the problem of variable name redefinition

3. Three access rights in the class,

Public: public access rights, mainly write some function interfaces

protected: protect access

private access encapsulation,

4. Constructor \ destructor

5. Overload operator

sub.h file

/*
    Implement a sequence table
    1.Create class. Member contains. Pointer to sequence table, length of sequence table, number of elements of sequence table
    2.Implementation functions: add, delete, modify, view
*/
//When declaring with header file,have access to ifnedf endif
#ifndef __SUB_H__    
/*
    #ifndef  Short for if not define 
    It is a conditional compilation of three preprocessing functions (macro definition, file inclusion, conditional compilation)
    Using it in C + + again can avoid "the error of repeated definition of variables"
*/
#define __SUB_H__
#include <iostream>
using namespace std;

//Use scope,Make sure the function name doesn't go wrong
namespace data
{
    //Establish vector class
    class vector
    {
        //Define private members,Include pointer to space,Space size,Number of space elements
    private:
        int *element = nullptr;
        size_t count = 0;    //size_t Is address line width int Is the data line width,
        size_t length = 0;
        //Insufficient new space to define protection member
    protected:
        bool re_new(int size);
        //Defining public member functions includes:Constructor,Destructor,Member other functions
    public:
        //The return value can be used uniformly as bool To determine function usage
        //The function of initializing destructor 
        //First of all,Initialize it,The default parameter is declared not to be used here
        vector(int count=10);

        //Destructor to release pointer and so on
        ~vector();

        //Order table add use bool Return value,Convenient to check whether the function runs successfully
        //Two parameters are required for insertion:Where to insert,What to insert
        bool insert(int index, int elem);

        //To delete a sequence table, you only need to insert the deletion location
        bool erase(int index);

        //heavy load[] Search and modify the content
        int & operator[](int index);
        //Number of viewing elements
        int Ssize()const { return length; }
        //Operator overloading ,Convenient output
        //Overloading with friend functions cout operator
        friend ostream & operator<<(ostream & o, const vector & vec);
    };

}

#endif // !__SUB_H__

sub.cpp file

#include "sub.h"
using namespace std;
//The leading class defines the scope,It needs to be used here to access
namespace data
{
    //Constructors need scopes to know where a function belongs
    vector::vector(int count )    //The parameter is already 10,In statement
    {
        //Initialize basic member variables
        //Because to use the count Assignment,Same variable name encountered,
        //Use this Pointer to distinguish.Yes this Pointer to a variable belonging to a class
        this->count = count;
        length = 0;        //Element number,Initial 0
        //Initializing pointers to sequential tablespaces
        //Request space in the heap,The space size is count 
        element = new int[count];  //  = {0}; Tedious initialization
        //Space initialization is required after space application \
         Use memset(Pointer variable,Initial value, Space size )
        memset(element ,0,sizeof(int)*count);
    }
    //Destructor destructor has no parameters, Construction with parameters,Variable parameters
    //Destructor    Used to free up space occupied by objects
    vector::~vector()
    {
        //First release the pointer to the space
        //Determine if the pointer is now empty
        if (element!=nullptr)
        {
            //Use new Apply, delete Release,
            //Square brackets are used here because when applying, Type is int[] 
            delete[] element;
        }
        //Number of initialization elements
        length = 0;
    }
    //Sequence table insertion\Add to
/*
    Consider:
    1.If the insertion position is appropriate, it is possible to insert the position of - 1. If the array subscript is at least 0, an error will occur if - 1
    2.Judge the space size, because the space size is the initial setting, it is possible that the data exceeds the
    3.The position of adding elements needs to be moved backward one bit for all elements in the back to be empty
    4.Assign the empty position to the required element
    5.Add element number + 1
    6.Return to success
*/
    //index Where to insert, elem Element content inserted for
    //Don't forget the scope of the class
    bool vector::insert(int index ,int elem)
    {
        //1.Location of judgement
        if (index<0 || index >length)
        {
            //Because it's not appropriate,So you need to exit the program
            return false;
        }
        //2.Judge the space size to see if the number of elements is equal to the space size,Equality indicates insufficient space
        if (length == count)
        {
            //Equality indicates insufficient space,Need to open up new memory
            //Use the member function of the class directly here, If you fail to open up space, please give me a hint
            if (!re_new(count+10))
            {
                printf("Space request failed!");
                //Use system Let the user see the prompt
                system("pause");
                //exit by C++Exit function for,exit(0)Normal exit,Non 0 abnormal exit
                exit(-1);
            }
        }
        //3.Insert position moves through loop traversal,position,Move position back
        //There i Need to equal the number of elements, Because the total length can find the corresponding location
        //When i When to the position to be inserted,Move backward once,You can get out of this position
        for (int i=length-1; i>=index; --i )
        {
            //Move the current location element to the next location,
            element[i + 1] = element[i];
        }
        //Insert position assignment
        element[index] = elem;
        //Because a content is inserted, the number of elements is required +1
        ++length;
        //Return to success
        return true;
    }
    //Delete elements
/*
    Consider:    
    1.Judge whether the position is valid
    2.The position to be deleted, one bit forward in sequence
        We need to pay attention to the problem of the last bit. Because it is moving forward in sequence, we need to assign the last bit to 0,
        That is to say: the next bit of the last element should also move forward to cover the original element
    3.Number of elements - 1
    4.Return to success
*/
    //Just delete the location
    bool vector::erase(int index)
    { 
        //1.Determine location because length How many elements are represented,therefore length -1 Is the location of the subscript
        if (index <0 || index >length-1)
        {
            return true;
        }
        //2.Delete elements
        for (int i =index;i<=length-1;i++ )
        {
            element[i] = element[i + 1];
        }
        //3.Element number -1
        --length;
        //4. Return to success
        return true;
    }
    //heavy load[] Easy access elements
    int & vector::operator[](int index)
    {
        //overload operators,Cannot change the properties of operators,
        //[]Is a subscript value,So it can be done here,Query and modify
        return element[index];
    }
    //Open up new space call this function to show that there is not enough space,Reallocation required
    bool vector::re_new(int size)
    {
        //Request heap space,Size is size It's a number that's 10 times larger than the original space,
        //If you want to make the program better,It needs to be set to twice the original number,Avoid multiple space allocations
        int* new_element = new int[size];
        //After applying for heap space,Initialization required memset
        memset(new_element , 0 , sizeof(int)*size);
        //We also need to check whether the space application is successful
        if (!new_element)  //Successful application returned 1,Take inverse,That's 0. ,Do not enter judgment
        {
            return false;
        }
        //Copy the contents of the original space to the new space for use memcpy function
        memcpy(new_element,element,this->count*sizeof(int));
        //Release the original space
        delete[] element;
        //Point pointer to new space
        element = new_element;
        //Don't forget here, Replace the original space with the new one
        this->count = size;
        //Return to success
        return true;
    }
    //Because this is a friend function,So it belongs to a global function,No class name scope required
    ostream& operator<<(ostream & o,const vector & vec)
    {
        for (int i=0;i<vec.Ssize();i++)
        {
            //endls Is to output a space 
            o << vec.element[i] << ends;
        }
        return o;
    }



}

main.cpp file

#include "sub.h"

int main()
{
    //Here you need to define the objects of the class
    //When an object is created,Constructor on execution
    data::vector vec(10);
    //Write element
    for (int i =0;i<30;i+=2)
    {
        vec.insert(0, i + 1);
    }
    //Operator overloaded,vec Can output directly
    cout << vec << endl;
    // Query location,The first few values
    cout << vec.operator[](5) << endl;
    //Set the value,How much to modify
    vec.operator[](5) = 555;
    cout << vec << endl;

    return  0;

}

Posted by bradley252 on Sat, 07 Dec 2019 08:31:59 -0800