C++:OOP+STL

First day of school! Evernote is too difficult to use, so let's move the notes here~

OOP

Object Oriented <-> Process for
IDE: Integrated Development Environment (be familiar to 1-2)
the STL: Standard Template Library
namespace : namespace
visible range of an identifier (operator namespace: :)
an effective solution to the problem of name collisions

void assert( int expression );

assert function: calculate expression, output error message if error occurs, call abort to terminate program operation

Mini.cpp program analysis

// a mini c++ program
#include <iostream>
int main()
{
    
    
    std::cout << "Hello, world!" << std::endl;
    return 0;   // 返回0表示运行成功
}

The header file suffix is ​​.h/.hpp or no suffix (standard header file). The
main function does not write return and returns 0 by default, which means the operation is successful

Stream output character <<

Binary operator, left associative, return value std::cout

cout<<"Hello World";
//左操作数cout(类似文件),右操作数字符串,将右输出到左
//返回值 std::cout
cout<<"Hello World"<<endl;
//第一次返回cout,右操作数endl,将右输出到左

string

String connection can be directly used +

string spaces(n,'char');
cout<<spaces;
//连续输出n个char字符
os<<s;//写入os输出流
is>>s;//读出is输入流
#include<iomanip>
cout<<setprecision(n)<<n;
//setprecision(n):设置输出有效数字
#include<iomanip>
#include<ios>
streamsize prec=cout.precision();
//std::streamsize:标准库内部定义的一个整数类型
//precision()返回当前浮点数精度
equal(a.begin(),a.end(),b.begin());
//提供a的收尾为比较范围,判断ab是否相等
equal(a.begin(),a.end(),b.begin(),b.end());
//要求容器相同,判断a,b是否相同

vector

Save multiple values ​​of the same type, variable length

vector<类型> 类型名;
vector.push_back(x);
#include<algorithm>
sort(vector.begin(),vector.end());
//默认非降序排序

vector.begin() the first element of the
container vector.end() the next position of the last element of the container

vector.erase(i);
//删除vector中元素
mid=size%2==0?(array[mid]+array[mid])/2:array[mid];
//求中值
vector.insert(ret.loc,const TYPE &val ); 
//在指定位置前加入val,返回指向这个元素的迭代器
vector.insert(ret.loc,int num,const TYPE &val); 
//在指定位置前加入num个val
vector.insert(ret.loc,input_iterator start,input_iterator end); 
//在指定位置前插入区间[start, end)的所有元素

list

Compare vector&list:list

map

Store the key-value collection (python's dict), each element is a pair, including two elements first and second (it->first, it->second)

Iterator

A design pattern that automatically returns to the next element, a smart pointer
that can sequentially access the elements in the container without exposing the internal expression of the container.
Five STL iterators:
input iterators (read data and point the iteration object down One)

for(istream_iterator<int>i=cin; i!=istream_iterator<int>(); ++i)
       v.push_back(*i);

Output iterator (data stored in sequence, can only write but not read, not rewind)

int tmp;
while(ifile>>tmp) cout<<tmp;

copy(istream_iterator<int>(ifile), istream_iterator<int>(),ostream_iterator<int>(cout));

Forward iterator (input + output)

void replace(FI first,FI last, const T& x,const T& y){
    
    
  for(;first!=last;++first)//输入
    if(*first==x)
			*first=y;//输出

Two-way iterator (access to elements in two directions, limited to single-step movement: list, set, multiset, map, multimap)

template<class BI,class Compare>
void bubble_sort(BI first,BI last, Compare comp){
    
    
	while(first != last){
    
    
		for(BI r = first+1;r!=last;r++){
    
    
			if(comp(*r,*(r-1)))
			{
    
     BI::value_type rv = *r; *r = *(r-1);
			*(r-1) = rv;
		} }
		first++; }
}

Random access iterator (access elements in two directions, can be accessed with any subscript: vector, deque)

vector<int>::iterator i=v.begin(); 
vector<int>::iterator j=i+2;
      cout<< *j<<"";
	  i+=3; 
	  cout<< *i<<"";

Insert picture description here

for(vector<int>::iterator iter(迭代变量名) = a.begin();iter != a.end(); ++iter)
{
    
    
    cout << *iter << endl;
}

Each STL container defines two iterators:

container-type::const_iterator//不可改变容器内值
container-type::iterator

abnormal

When an exception is thrown, the program will stop at the place where the exception occurred and send the exception object

throw domain_error("median of an empty vector");
//domain_error: 用来说明一个函数的实参是这个函数不能接受的。

try-catch:

try{
    
    
	}catch(异常类型){
    
    }

Try to execute the function statement after try, if there is an exception, it will jump to execute the statement in the catch, if there is no exception, skip the catch directly

Unnamed object

cout<<string(maxlen+1-students[i].name.size(),' ');
//变量的名字是spaces(?)

Quote

An alias for the object, pointing to the same memory unit. The
main purpose: to allow the function to set the reference parameter (parameter == actual parameter)

数据类型 & 标识符(左值表达式);
数据类型 & 标识符=左值表达式;

Different from the pointer:
references must be initialized, can point to NULL pointer
references can not change the mapping , you can change the pointer points to
references not cited, (?) Pointer is not referenced , the array does not refer to the

const int &s1=s2;
const int &s3=s1;
int &s4=s1;//错误!静态变量必须由静态变量引用
//保证不会改变s1的值

The reference parameter must accept an lvalue

When the function return value is a reference: the
function call can appear on the left side of the equation and
cannot return a reference
to the local variable inside the function . No temporary object is generated when returning

Three forms of function parameters

double fun(int a){
    
    }

Copy the actual parameters without changing the actual parameters

double fun(int &a){
    
    }

Do not copy the actual parameters, change the actual parameters

double fun(const int &a){
    
    }

Do not copy actual parameters, do not change actual parameters


Overload

Same function name, different parameter list

random number

Computer random numbers are pseudo-random numbers
Monte Carlo method

srand(unsigned(yime(0)));//使用前要随机化,否则产生的序列是相同的
int i=rand(1000);

find-if

Search for arrays and STL containers

#include <algorithm>

list<int>::iterator it = find(lst.begin(), lst.end(), 10); 
// 查找list中是否有元素10
// find函数没有找到对应值,返回第二个参数
list<CPerson*>::iterator it = find_if(lst.begin(),lst.end(), func);
// 自行定义查找,func为谓词,返回第一个让func返回true的值
isspace(char c) //库函数,检查所传的字符是否是空白字符

isspace is an overloaded function (supports multiple data types), it cannot be used as a predicate and needs to be repackaged

Generic function

I don’t know the parameter type and return value type (such as the find function)
before use . General form: the first two parameters are a pair of iterators, representing the range of algorithm operation [first, last).
Function generalization: parameter data type abstraction + operation Object representation and behavior abstraction

Generic Algorithm

It acts on iterators instead of containers.
Mainly: constant value algorithms, variable value algorithms, sorting algorithms, numerical algorithms
vector and deque support random iterators;
list, map, set, multimap and multiset support bidirectional iterators.
Iterator support methods: begin()/end() and rbegin()/rend();


Class discussion in the first week

The freshman classmates are really too active... asked so many questions...(・-・*)

endl :
endl is a stream operator. The buffer area is cleared at the same time as the output (flush can also be called). When the
program exits normally, the buffer area is automatically cleared.

Guess you like

Origin blog.csdn.net/Rachel_IS/article/details/104473642