Python to C++ format study notes

I mainly write python, but I feel that if I want to improve the algorithm, I still have to write it in c++, so the notes mainly record the difference between c++ and python. , inside the white box is your own understanding, everyone takes the essence and discards the dross

head File

include <iostream>   /主要包含cin和cout基本输入输出流
include <cstdio>     /主要包含scanf和printf输入输出函数

When the data scale is large, the speed of scanf and printf is much faster than that of cin and cout, but after I personally did some questions, there was no such reason that caused a timeout, so I can use it according to my own habits (personally, if the
output There are format requirements, such as floating-point numbers, use printf, and I am used to using cout, because it is faster to write)

using namespace std;

If you are interested in the function of this statement, you can check it yourself. Some compilers add it by default, but I am used to writing it myself.

Universal header file, including all library functions that may be used by C++

#include <bits/stdc++.h>

main function

basic format

! Note that variables must be defined in advance

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    
    
	int n;
	cin >> n; /输入
	cout << n << endl; /输出
	return 0;
}

cycle

eg: print prime numbers within 1-100

insert image description here

array

Initialize the array

insert image description here
array operation

访问数组的方式与python一致
/求元素个数
cout << sizeof(arr) / sizeof(arr[0]) << endl; 

Multidimensional Arrays

insert image description here

character array

A string is an array of characters plus the terminator '\0'.
Strings can be used to initialize character arrays, but at this point, it should be noted that a '\0' character is implied at the end of each string, so the length of the character array must be at least 1 more than the length of the string!

insert image description here

Common operations on character arrays

下面几个函数需要引入头文件:
#include <string.h>
(1)	strlen(str),求字符串的长度
(2)	strcmp(a, b),比较两个字符串的大小,a < b 返回-1,a == b 返回0,a > b返回1。这里的比较方式是字典序!
(3)	strcpy(a, b),将字符串b复制给从a开始的字符数组。

String type string

A variable-length character sequence is more useful than a character array. Need to import header files:
#include < string>

get string

getline(cin, num);

/其中 cin 是正在读取的输入流,而 num 是接收输入字符串的 string 变量的名称

insert image description here
output the entire string

#include < iostream>
#include < string>

using namespace std;

int main()
{
    
    
    string s1;
    
    cin >> s1;

    printf("%s", s1.c_str());
    
    return 0;
}

String construction assignment + splicing

#include <string>

void text2()
{
    
       
    string s1;
    s1 = "hello world";
    s1 += "C++"

    const char * str = "hello world"; /const 限定符,它把一个对象转换成一个常量
    string s2(str);

    string s3(s2);

    string s4(5,'a'); /aaaaa
}

other operations

1)查找
string str1 = "abcdef";
int a = str1.find("def");
2)替换
string str2 = "aaabbb"
str2.replace(3,3,"aaa")
3)比较
str1.compare(str2) == 0相等
>0 str1大
<0 str2大
4)字符存取
string str1 = "hello";
for (int i = 0; i < str.size(); i++)
{
    
    
    cout << str[i] << " ";
    cout << str.at(i) << " ";
} 
cout << endl;
5)字符串修改
str[0] = 'a';
6)插入,删除
string str = "hello";
str.insert(1,"zzz");
sr.erase(1,3) //开始位置,几个
7)求字串
string str = "abcdefg";
string s = str.substr(1,3);
8)count
count(s.begin(),s.end(),'a');

C++ STL

STL is a sharp tool to improve the efficiency of C++ writing. - total

1) vector container

structure

void text3()
{
    
    
    vector<int>v1; /默认构造,无参构造
    for (int i = 0; i < 10; i++)
    {
    
    
        v1.push_back(i)
    }
    printVector(v1);

    /通过区间方式进行构造
    vector<int>v2(v1.begin(),v1.end());

    /n个elem方式构造
    vector<int>v3(10,100);

    /拷贝构造
    vector<int>v3(v4);
}

traverse

#include <vector>
#include <algorithm> /标准算法头文件

void myPrint(int val)
{
    
    
    cout << val << endl;
}


void text1()
{
    
    
    vector<int> v;
    /向容器中插入数据
    v.push_back(10);
    v.push_back(20);

    /通过迭代器访问容器中的数据
    vector<int>::iterator itBegin = v.begin(); /起始迭代器,指向容器中第一个元素
    vector<int>::iterator itEnd = v.end(); //结束迭代器,指向容器中最后一元素的下一个位置

    /遍历方式一
    while (itBegin != itEnd)
    {
    
    
        cout << *itBegin << endl;
        itBegin++;
    }

    /遍历方式二
    for(vector<int>::iterator it = v.begin(); it != v.end();it++)
    {
    
    
        cout << *it << endl;
    }

    /遍历方式三
    for_each(v.begin(), v.end(), myPrint);
}

Other operation functions

size()/empty()
size函数返回vector的实际长度(包含的元素个数),empty函数返回一个bool类型,表明vector是否为空。二者的时间复杂度都是O(1)。

所有的STL容器都支持这两个方法,含义也相同,之后我们就不再重复给出。
begin()/end()
begin函数返回指向vector中第一个元素的迭代器。例如a是一个非空的vector,则*a.begin()与a[0]的作用相同。
front()/back()
front函数返回vector的第一个元素,等价于*a.begin() 和 a[0]。
back函数返回vector的最后一个元素,等价于*==a.end() 和 a[a.size()1]
push_back()pop_back()
a.push_back(x) 把元素x插入到vector a的尾部。
b.pop_back() 删除vector a的最后一个元素。
sort()排序
#include <algorithm>
sort(d.begin(), d.end());
/倒序
sort(d.rbegin(),d.rend());
用swap收缩内存
vector<int>(v).swap(v);
预留空间
v.reserver(10000)

2) set container

Features, elements are automatically sorted when they are inserted, and duplicate values ​​are not allowed

Duplicate values ​​are not allowed to be common between c++ and python, but python's set is unordered, while c++ is ordered

The header file set mainly includes two containers, set and multiset, which are "ordered set" and "ordered multiset", that is, the elements of the former cannot be repeated, while the latter can contain several equal elements. The internal implementation of set and multiset is a red-black tree, and the functions they support are basically the same.

#include<set>
set<int>s;
/插入数据
s.insert(10);
s.insert(20);
/拷贝构造
set<int>s2(s1);
/判断为空
if (s.empty())
/大小
s.size()
insert(elem) //插入
clear() /清除所有元素
erase(pos) / 删除pos迭代器所指的元素,返回下一个元素的迭代器 s.begin() s.end()
erase(begin,end) /删除区间所有元素,返回下一个元素的迭代器
erase(elem) /删除容器中值为elem的元素
find() //不存在返回set.end()
count() //统计个数0/1
lower_bound()/upper_bound()
这两个函数的用法与find类似,但查找的条件略有不同,时间复杂度为 O(logn)。
s.lower_bound(x) 查找大于等于x的元素中最小的一个,并返回指向该元素的迭代器。
s.upper_bound(x) 查找大于x的元素中最小的一个,并返回指向该元素的迭代器。
/利用仿函数指定set容器的排序规则

class MyCompare
{
    
    
public:
    bool operator()(int v1, int v2) const
    {
    
    
        return v1 > v2;
    }
}
set<int,MyCompare>s2;

3) deque container

A double-ended queue deque is a continuous linear storage space that supports efficient insertion or deletion of elements at both ends. It's like a combination of vector and queue. Compared with vector, deque only needs O(1) time to add and delete elements at the head; compared with queue, deque supports random access like an array.

[] 随机访问
begin/end,返回deque的头/尾迭代器
front/back 队头/队尾元素
push_back 从队尾入队
push_front 从队头入队
pop_back 从队尾出队
pop_front 从队头出队
clear 清空队列

4) map container

The map container is a key-value pair key-value mapping, and its internal implementation is a red-black tree with key as the key code. The key and value of Map can be of any type.

声明
map<key_type, value_type> name;
例如:
map<long, long, bool> vis;
map<string, int> hash;
map<pair<int, int>, vector<int>> test;
size()/empty()/clear()/begin()/end()均与set类似。
insert()/erase()
与set类似,但其参数均是pair<key_type, value_type>
find()
h.find(x) 在变量名为h的map中查找key为x的二元组。
[]操作符
h[key] 返回key映射的value的引用,时间复杂度为O(logn)[]操作符是map最吸引人的地方。我们可以很方便地通过h[key]来得到key对应的value,还可以对h[key]进行赋值操作,改变key对应的value。

Supplementary knowledge points

#include <cmath > Contains some commonly used mathematical functions

1ceil(x)      /向上取整 
2floor(x) 	/向下取整
3fabs(x) 		/x的绝对值 
4sqrt(x) 		/x的平方根 
5pow(x,y) 	/x的y次幂

Definition and input and output of floating point numbers

double r;
scanf("%lf", &r);
printf("%.4lf", r * r); /四位小数;
/%8.3f, 表示这个浮点数的最小宽度为8,保留3位小数,当宽度不足时在前面补空格
/%-8.3f,表示最小宽度为8,保留3位小数,当宽度不足时在后面补上空格
/%08.3f, 表示最小宽度为8,保留3位小数,当宽度不足时在前面补上0

Generate random numbers

#include <stdlib.h>
#include <ctime>

srand((unsigned int) time(NULL)); /添加随机数种子,防止每次随机数一样
int num = rand()%100  /生成0 ~ 99随机数

Guess you like

Origin blog.csdn.net/qq_46500711/article/details/128583186