C + + Basics (advanced tutorial / STL) -- Based on Java && C Basics

Posted by dhimok on Tue, 02 Nov 2021 10:27:10 +0100

Advanced tutorial

1. Files and streams

data typedescribe
ofstreamThis data type represents the output file stream, which is used to create a file and write information to the file.
ifstreamThis data type represents an input file stream for reading information from a file.
fstreamThis data type usually represents a file stream and has both ofstream and ifstream functions, which means that it can create a file, write information to the file and read information from the file.

To process files in C + +, you must include header files < iostream > and < fsstream > in the C + + source code file.

void open(const char *filename, ios::openmode mode);
void close();
Mode flagdescribe
ios::appAppend mode. All writes are appended to the end of the file.
ios::ateAfter the file is opened, navigate to the end of the file.
ios::inOpen the file for reading.
ios::outOpen file for writing.
ios::truncIf the file already exists, its contents will be truncated before opening the file, that is, set the file length to 0.
// Receive stream data
char data[100];

// Open file in write mode
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
// Write user input data to the file
outfile << data << endl;
// Close open files
outfile.close();

// Open file in read mode
ifstream infile; 
infile.open("afile.dat"); 
cout << "Reading from the file" << endl; 
infile >> data; 
// Write data on screen
cout << data << endl;
// Close open files
infile.close();

File location pointer
Both istream and ostream provide member functions for relocating file location pointers. These member functions include seekg ("seek get") for istream and seekp ("seek put") for ostream.

// Locate the nth byte of fileObject (the default direction is ios::beg)
fileObject.seekg( n );
 
// Move the file read pointer back n bytes from the current position of fileObject
fileObject.seekg( n, ios::cur );
 
// Move the read pointer of the file back n bytes from the end of fileObject
fileObject.seekg( n, ios::end );
 
// Navigate to the end of fileObject
fileObject.seekg( 0, ios::end );

2. Exception handling

Exceptions to the C + + standard
C + + provides a series of standard exceptions, which are defined in. We can use these standard exceptions in programs. They are organized in a parent-child hierarchy as follows:

The following table describes each exception in the above hierarchy:

abnormaldescribe
std::exceptionThis exception is the parent of all standard C + + exceptions.
std::bad_allocThis exception can be thrown through new.
std::bad_castThe exception can be passed through dynamic_cast throw.
std::bad_exceptionThis is useful when dealing with unexpected exceptions in C + + programs.
std::bad_typeidThis exception can be thrown through typeid.
std::logic_errorIn theory, exceptions can be detected by reading the code.
std::domain_errorThis exception is thrown when an invalid mathematical field is used.
std::invalid_argumentThis exception is thrown when an invalid parameter is used.
std::length_errorThis exception is thrown when too long std::string is created.
std::out_of_rangeThis exception can be thrown through methods, such as std::vector and STD:: BitSet < >:: operator .
std::runtime_errorExceptions that cannot theoretically be detected by reading code.
std::overflow_errorThis exception is thrown when a math overflow occurs.
std::range_errorThis exception is thrown when an attempt is made to store a value that is out of range.
std::underflow_errorThis exception is thrown when a mathematical underflow occurs.
// Custom Exception
struct MyException : public exception
{
  const char * what () const throw ()
  {
    return "C++ custom defined Exception";
  }
};
 
int main()
{
  try
  {
    throw "string exception";
    throw MyException();
  }
  catch(const char* e)
  {
      std::cerr << e << '\n';
  }
  catch(MyException& e)
  {
    std::cout << "MyException caught" << std::endl;
    // what() is a public method provided by the exception class, which has been overloaded by all child exception classes
    std::cout << e.what() << std::endl;
  }
  catch(std::exception& e)
  {
    //Other exception s and their subclasses
  }
  catch(...)
  {
    //Other exception s
  }
}

3. Dynamic memory

The memory in C + + programs is divided into two parts:
Stack: all variables declared inside the function will occupy stack memory.
Heap: This is unused memory in the program, which can be used to dynamically allocate memory when the program is running.

int main() {
    int *ptr = NULL;
    // Allocate memory
    ptr = new int;
    // Judge whether the memory allocation is successful
    if (!ptr) {
        exit(-1);
    }
    *ptr = 12;
    // Free memory
    delete ptr;

    return 0;
}
// One dimensional array
// Dynamic allocation, array length m
int *array=new int [m];
 
//Free memory
delete [] array;

// Two dimensional array
int **array;
// Suppose the length of the first dimension of the array is m and the length of the second dimension is n
int m = 3, n = 5;
// Dynamically allocate space
array = new int *[m];
for( int i=0; i<m; i++ )
{
    array[i] = new int [n]  ;
}
//release
for( int i=0; i<m; i++ )
{
    delete [] array[i];
}
delete [] array;
// Allocate memory space for objects
class Box
{
    int width;
    int height;
    public:
        void setWidth(int w);
        void setHeight(int h);
        int getArea();
};

    Box* box = new Box;
    box->setWidth(2);
    box->setHeight(3);
    std::cout << "box area: " << box->getArea() << std::endl;
    delete box;

4. Namespace

#include <iostream>
using namespace std;

// Namespace definition, using the keyword namespace
namespace first_space{
   void func(){
      cout << "Inside first_space" << endl;
   }
}

int main ()
{
   // Call function / variable in namespace
   first_space::func();
   return 0;
}
==>
// using namespace xxx
using namespace first_space;
int main ()
{
   // using, first_space::func();
   func();
   return 0;
}

5. Formwork

Templates are the foundation of generic programming, which is writing code in a way independent of any particular type.

Templates are blueprints or formulas for creating generic classes or functions. Libraries, such as iterators and algorithms, are examples of generic programming. They all use the concept of templates.

Each container has a single definition, such as vector. We can define many different types of vectors, such as vector or vector.

Function template

// General form of template function definition
template <typename type> ret-type func-name(parameter list)
{
   // Body of function
}

// Example
template <typename T>
inline T const& Max (T const& a, T const& b) 
{ 
    return a < b ? b:a; 
} 

Class template

template <class type> class class-name {
	// xxxxx
}


// Example
template <class T>
class Stack { 
  private: 
    vector<T> elems;     // element 
 
  public: 
    void push(T const&);  // Push 
    void pop();               // Out of stack
    T top() const;            // Return stack top element
    bool empty() const{       // Returns true if empty.
        return elems.empty(); 
    } 
}; 

// Implementation of Stack::push
template <class T>
void Stack<T>::push (T const& elem) 
{ 
    // Append a copy of the incoming element
    elems.push_back(elem);    
} 

int main() 
{ 
    try { 
        Stack<int>         intStack;  // Stack of type int 
        Stack<string> stringStack;    // Stack of type string 
         // Stack of operation int type 
        intStack.push(7); 
    } 
    catch (exception const& ex) { 
        cerr << "Exception: " << ex.what() <<endl; 
        return -1;
    } 
}

6. Preprocessor

C + + also supports many preprocessing instructions, such as #include, #define, #if, #else, #line, etc.

#define PI 3.14159
cout << "Value of PI :" << PI << endl; 

#define MIN(a,b) (a<b ? a : b)
cout <<"The smaller values are:" << MIN(i, j) << endl;

#define DEBUG
// Conditional compilation
#ifdef DEBUG
   cerr <<"Variable x = " << x << endl;
#endif

#if 0
   Code not compiled
#endif

// #The operator converts the replaced token into a quoted string, i.e. "x"
#define MKSTR( x ) #x
// ##Operator is used to connect two tokens, xy
#define CONCAT( x, y )  x ## y

Predefined macros in C + +

macrodescribe
__LINE__This will include the current line number when the program is compiled.
__FILE__This will include the current file name when the program is compiled.
__DATE__This will contain a string in the form of month/day/year, which represents the date when the source file was converted to the object code.
__TIME__This will contain a string in the form of hour:minute:second, which represents the time when the program was compiled.

7. Signal processing

A signal is an interrupt sent by the operating system to a process that terminates a program early.
Some signals cannot be captured by the program, but the signals listed in the table below can be captured in the program and appropriate actions can be taken based on the signals. These signals are defined in the C + + header file.

signaldescribe
SIGABRTAbnormal termination of the program, such as calling abort.
SIGFPEIncorrect arithmetic operations, such as dividing by zero or operations that cause overflow.
SIGILLDetect illegal instructions.
SIGINTProgram interrupt signal.
SIGSEGVIllegal access to memory.
SIGTERMTermination request sent to the program.

Register signal: signal() function
void (*signal (int sig, void (*func)(int)))(int);
Generate signal: raise() function
int raise (signal sig);

#include <iostream>
#include <csignal>
#include <unistd.h>
 
using namespace std;
 
void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";
    // Clean and close
    // Termination procedure  
   exit(signum);  
}
 
int main ()
{
    // Register signal SIGINT and signal processing function signalHandler
    signal(SIGINT, signalHandler);  
 
    while(1){
       cout << "Going to sleep...." << endl;
       if( i == 3 ){
          // Generate signal
          raise( SIGINT);
       }
       sleep(1);
    }
 
    return 0;
}

8. Multithreading

https://www.runoob.com/cplusplus/cpp-multithreading.html

9. Web programming

https://www.runoob.com/cplusplus/cpp-web-programming.html

Standard template library (STL)

1. STL tutorial

https://www.runoob.com/cplusplus/cpp-stl-tutorial.html

2. Standard library

https://www.runoob.com/cplusplus/cpp-standard-library.html

3. Useful resources

C + + useful website
C++ Standard Library headers − C + + standard library.
C++ Programming − this book covers C + + language programming, software interaction design, and real-life applications of C + + language.
C++ FAQ − C + + frequently asked questions
Free Country − Free Country provides free C + + source code and C + + libraries, which cover C + + programming fields such as compression, archiving, game programming, standard template library and GUI programming.
C and C++ Users Group − C and C + + user groups provide free source code for C + + projects covering various programming fields, including AI, animation, compiler, database, debugging, encryption, games, graphics, GUI, language tools, system programming, etc.

C + + useful books
Essential C + + Chinese version
C++ Primer Plus version 6 Chinese version
C++ Primer Chinese Version (5th Edition)

4. Examples

https://www.runoob.com/cplusplus/cpp-examples.html

reference resources:
Rookie tutorial - C + + tutorial

Topics: Java C C++