Introduction

//use compiler g++
//compile with the option -std=c++11

可以用github to back up the code privately

Quiz: integer division: 1/2=0; double division: 一切正常

\(p_{38}\) :comments, consistency, indentation, meaningful meaning (the name of variables/functions should be clear)

Linux

Unix: an operating system supporting multitasking and multi-user

Linux: a free and open source Unix-like operating system

Commands:

cd / 
cd /user/bin #typical path name format
pwd #show the current path
ls #show directories
cd home
cd .
cd ..
# / root directory
# ~ home directory

list contents of the directory:

ls: list the current working directory

hidden files begin with a dot

ls name_of_directory
ls /home
ls //

ls -l
ls -a #list all files including the hidden file
ls -l name_of_directory
ls -a name_of_directory

#combine options:
ls -la
ls -l -a

#equivalent:
ls ~
ls /home/hermione

ls -l ~
ls -a ~
ls -la ~
hermione@LAPTOP-7C446K4N:/$ ls -la /home/hermione
total 8
drwxr-xr-x 1 hermione hermione 4096 Sep  8 14:35 .
drwxr-xr-x 1 root     root     4096 Sep  8 14:33 ..
-rw-r--r-- 1 hermione hermione  220 Sep  8 14:33 .bash_logout
-rw-r--r-- 1 hermione hermione 3771 Sep  8 14:33 .bashrc
drwxr-xr-x 1 hermione hermione 4096 Sep  8 14:35 .landscape
-rw-rw-rw- 1 hermione hermione    0 Sep  8 14:35 .motd_shown
-rw-r--r-- 1 hermione hermione  807 Sep  8 14:33 .profile

permission: 3 types - read: cannot change; - write: can change

manipulating files/directories:

Create directories: mkdir learningsources
Delete directories: rmdir learningsources
# can only delete empty directory
Create an empty file: touch VV285
hermione@LAPTOP-7C446K4N:/home$ cd hermione
hermione@LAPTOP-7C446K4N:~$ mkdir learningsources
hermione@LAPTOP-7C446K4N:~$ cd learningsources
hermione@LAPTOP-7C446K4N:~/learningsources$ touch VV285
check if it's an empty file: ls -l

copy files/directories:

cp file1 file2 #copy the content of file1 into file2
cp file1 dir1 #copy file into a directory
cp file1 file2 dir #back up files into the same directory
cp file* dir #can represent any character spring (before the dot)
cp -r dir1 dir2 #if dir2 doesn't exist, copy dir1 as dir2; if dir2 exists, copy dir1 inside dir2

# cp dir1 dir2错误,没有指定option

Rename/Move a file

mv file1 file2 #change the file name
mv file1 dir #move file into a directory
mv dir1 dir2 #if dir2 not exist, rename dir1 into dir2; if dir2 exists, move dir1 inside dir2

Delete files/directories

rm file #delete file
rm file1 file2 #delete at the same time
rm -r dir #delete dir along with its contents (delete iteratively

#opportunity to recover:
rm -i file

alias rm='rm -i'
rm file

hermione@LAPTOP-7C446K4N:~$ gedit .bashrc

.bashrc的用途:

https://blog.csdn.net/qing101hua/article/details/53086318

Edit/Show a file

#edit file:
nano file
gedit file

#show file:

sort用法

https://www.runoob.com/linux/linux-comm-sort.html

Linux 9.15

# install a program
sudo apt-get install <programname>

# remove a program
sudo apt-get autoremove <programname>

sudo # execute <command> as a superuser, requiring to type in password

# look for help, the manual of a command
man <command>

Developing and compiling programs on Linux

gedit #write the source code
g++ -o <program> <source.app> #compile the program, using compiler g++
#-o option tells what the name of the output file is

./<program> #run the program
ls
vim hello_world.cpp
g++ -o hello hello_world.cpp
ls #hello hello_world.cpp
ls -l 
./hello #run the hello program in the current directory
hello #error! command not found

#若编译的文件错误,则编译时会报错,no executable program generated
ls #hello_world.cpp
vim hello_world.cpp
g++ -o hello hello_world.cpp

#
rm hello
#useful options of g++
-g #put debugging information in the executable file
-Wall #turn on all warnings

g++ -Wall -o hello hello_world.cpp
g++ -c <source.cpp> #a hello_world.o in the directory
g++ -o <program> <source.o> 

multiple source files:

#Problems of multiple inclusions
g++ -o main main.cpp point.h line.h
g++ -o main main.cpp #更好,因为已经包括了
#如果两个.h都包含同一个class,则会报错

#solution: header guard
//add.h
#ifndef ADD_H
#define ADD_H
int add(int a, int b);
#endif

compile multiple source files:

g++ -Wall -o program src1.cpp src2.cpp src3.cpp
//define a function: 不需要include <head.h> file

Makefile用法

https://blog.csdn.net/wangqingchuan92/article/details/92832544

Review of c++ basics

Very basic concepts:

variables built-in data types operators

y=x++;
//y=x;x=x+1;

y=++x;
//x=x+1;y=x;

expression

a*b+c; “a”; 5; f(a,b)

//    (both left and right) and rvalue (only right)
//any non-constant variable is an lvalue.
//any constant is an rvalue.

a+1: rvalue

a+b: rvalue

c[2*3]: lvalue

function

function declarations and definitions

function declaration: must appear in the code before the function can be called

Return_Type Function_Name (Parameter_List);

function definition: can appear before or after it is called

Return_Type Function_Name (Parameter_List){

}

void: return nothing, but can have the order “return” (return types can be “void”).

void foo(){
    if(a==1){
        return;
    }
    //other codes
}

//or: omit the return when we need to reach the end of the function:
void foo(){
    //codes
}

function declaration: formal parameter names; type signature: return type, how many arguments are needed, types of the arguments

function definition: function header; function body

function call mechanisms

https://www.sohu.com/a/277358503_641197函数调用三种方式比较

(1)如果一个函数定义在先,调用在后,调用前可以不必声明。 (2)如果一个函数定义在后,调用在先,调用前必须声明

//call by value
void f(int x){
    x *=2;
}

//call by reference
void f(int& x){
    x*=2;
}

int main(){
    int a=4;
    f(a);
}

/*
    by value: when function finishes, the variable is deleted
    reference: alias
    
*/
//call by pointer
void swap_pointer(int *x, int *y){
    int temp;
    temp= *x;
    *x=*y;
    *y=temp;
}
//call by reference
void swap_reference(int &x, int &y){
    int temp;
    temp=x;
    x=y;
    y=temp;
}

int main(){
    int a,b;
    a=3; b=5;
    swap_pointer(&a,&b);
    swap_reference(a,b);
    cout<<a<<b<<endl;
    return 0;
}

array

array: fixed-sized, indexed data type that stores a collection of items, all of the same type

//declaration:
int b[4];

//access:
b[i];

c++ arrays can be passed as arguments to a function

int sum(int a[], unsigned int size);
//unsigned: 必须是非负,使得array可以有更大的size,更安全

array is passed by reference

b= [7,7,3,4];

void add_one(int a[], unsigned int size){

}

add_one(b,4) : by reference

pointers

pointers: working with address \(p_{12}\)

int foo = 1;
int *bar; //define a pointer
bar = &foo; //addressing operation,获得&foo 的alias
*bar = 2; //dereference operation
  • pointer doesn’t need to be initialized

  • reference must be defined with initialization using a variable(不能为number, number 10 is nor a variable) of the same type!

references: alias for an object

int ival = 1024;
int &refval = ival;
//refval=1 即为ival=1

//int &refval2; //error: not initialized
//int &refval3 = 10; //error: 10 is not a variable

there is no way to rebind a reference to a different object after initialization

int ival = 1024;
int &refval = ival;
int ival2 = 10;
refval = ival2; //refval still binds to ival, not ival2

compare pointers and references

  • both pointers and references allow you to pass objects by reference

    void f(int *x){
    *x *=2;
    }
    
    int main(){
        int a=4;
        f(&a);
    }
    
    //pointers require some extra syntax at calling time (&), in the argument list (*), and with each use (*); references only require extra syntax in the argument list (&).
    
    //pointer can rebind!
    int *p=&x;
    p=&y;
    
    //you can change the object to which a pointer points, but you can not change the object ot which a reference refers.
    

    comparison

    //reference
    int x=0;
    int &r=x;
    int y=1;
    r=y;
    r=2;
    //x=2, y=1, r=2
    
    //pointer
    int x=0;
    int *p=&x;
    int y=1;
    p=&y;
    *p=2;
    //x=0, y=2, *p=2

    advantages of pointers:

    • convenient mechanism to work with arrays
    • can create structures whose size is not known in advance

pointers and arrays

int array[4];
array=&array[0];
*(array+i)=array[i];

structs

to create a compound type

struct Grades {
    char name[9];
    int midterm;
    int final;
};//要有;
//type != object
//the statement declares the type "struct grades", but doesn't declare any objects of that type

//we can define single object of this type as:
struct Grades alice;
//大小写区分type和object

//initialize:
struct Grades alice={"Alice", 60, 85};

//after we have a struct, we can access its individual components using:
alice.midterm=65; //change 原先的 to 65

//if you have a pointer to a struct, visit component using:
struct Grades *gPtr = &alice;
gPtr->final=90;

const qualifier

constant number

numerical value which has some valid meaning:

char name[256];
//缺点:如果改变,需要一个一个改,且容易误改

const int MAXSIZE=256;
char name[MAXSIZE];
//constant often global, but also can be local
//cannot be modified later on
const int a=10;
a=11; //error
//must be initialized when it is defined
const int i; //error

const reference

const int ival=10;
const int &rval=ival;

//true:
const int &ref =10;
const int &ref = ival+10;

//false:
int &ref=10;
int &ref=ival=10;//expression is not a lvalue
//practical use of const reference
//best:
int avg_exam(const struct Grades & gr){
    reutrn (gr.midterm+gr.final)/2;
}
//好处:1. without expense of a copy
//2. guarantee that the funciton cannot change the caller's state


//bad:
int avg_exam(struct Grades gr){}
//pass by value: memory additional, more time

int avg_exam(struct Grades & gr){}
//pass by reference: 可以修改variable的内容,但对于不想要改变该数值的函数来说这样做就会有风险
//for non-const reference, function call with consts or expressions is not ok.
foo("hello world!"); //这是一个const string,是rvalue
void foo(string & str){} //error,因为const reference can be initialized to an rvalue, but nonconst reference cannot be initialized to an rvalue
void foo(const string &str){} //right!

//理解
const int &ref=10; //right
int &ref=10; //error
//demo:
#include <iostream>
#include <string>
using namespace std;

void foo(string &input){
    cout << input << endl;
}

void bar(const string &input){
    cout << input << endl;
}
int main(){
    //const int &rval=2+3;
    //cout<<rval<<endl; 
    //string str = "hello world!";
    //foo(str); //right
    //bar(str); //right
    //foo("hello world!"); //wrong
    //bar("hello world!"); //right

    return 0;
}

constant pointer

things can change:

  • the value of the pointer
  • the value of the object to which the pointer points

pointer to const & const pointer:

https://blog.csdn.net/ace13527/article/details/102256490区别

//pointer to const 相对位置:const在*前面
const T *p;
T const *p;
//the pointed-to object cannot be changed by pointer p

//const pointer 相对位置:const在*后面
T *const p;
//the pointer cannot be changed

const T *const p;
//neither cna be changed
p=&b;
//p=&a;
//*p=20;

pointers to const

int a=53;
const int *cptr=&a; //ok, a pointer to a const object can be assigned the address of a nonconst object
*cptr=42; //error, we cannot use a pointer to const to change the underlying object
a=28; //ok, however we can directly change it by itself
int b=39;
cptr=&b; //ok, the value in the pointer can be changed

const to pointers

int a=53;
int *const cptr=&a; //ok, initialization
*cptr=42; //ok, we can use a const pointer to change the underlying object
int b=39;
cptr=&b; //error, we cannot change the value of a const pointer

define pointers to const using typedef:

  • define pointer to const:

    typedef const T consT_t;
    typedef consT_t * ptr_consT_t;
    //之后可以使用ptr_consT_t 作为const T *的别名(pointer to const)

Enumerator

https://www.runoob.com/w3cnote/cpp-enum-intro.html

枚举常量只能以标识符形式表示,而不能是整型、字符型等文字常量。例如,以下定义非法:

enum letter_set {'a','d','F','s','T'}; //枚举常量不能是字符常量
enum year_set{2000,2001,2002,2003,2004,2005}; //枚举常量不能是整型常量

可改为以下形式则定义合法:

enum letter_set {a, d, F, s, T}; 
enum year_set{y2000, y2001, y2002, y2003, y2004, y2005};
  • 不能直接将常量赋给枚举变量。如: color1=1; //非法

  • 不同类型的枚举变量之间不能相互赋值。如: color1=color3; //非法

  • 枚举变量的输入输出一般都采用switch语句将其转换为字符或字符串;枚举类型数据的其他处理也往往应用switch语句,以保证程序的合法性和可读性。

  • int i=suit //将枚举变量赋值给整型变量

define an enumeration type:

enum Suit_t {CLUBS, DIAMONDS, HEARTS, SPADES};

define variables of this type:

enum Suit_t suit;

initialize:

enum Suit_t suit = DIAMONDS

enums are passed by value and can be assigned

Aim: remove the REQUIRES clause.

Abstract data types

types: values and operations