C++琐碎知识点
vscode多文件编译
在task.json文件中编辑为如下形式
基础部分注意点
在使用函数引用时注意
void sswap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 3, b = 6;
sswap(a , b ); //不能写成 sswap(a+1,b+33)
return 0;
}
链表
C++单链表创建删除插入显示长度和打印操作
#include<iostream>
#include<cstring>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) :val(x), next(NULL) {}
};
ListNode* creat() {
ListNode* head, * p;
int val[] = { 1,2,3,4,5,6 };
head = new ListNode(val[0]);
p = head;
for (int i = 1; i < 6; i++) {
ListNode* s = new ListNode(val[i]);
p->next = s;
p = s;
}
p->next = NULL;
return head;
}
void print(ListNode *head) {
ListNode* p;
p = head;
//不能填while(p->next!=NULL)因为当到最后一个节点时p->next就成立了不往下执行了
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout <<endl;
}
int length(ListNode* head) {
ListNode* p = head;
int count=0;
//不能填while(p->next!=NULL)因为当到最后一个节点时p->next就成立了不往下执行了
while (p != NULL) {
count++;
p = p->next;
}
return count;
}
ListNode* insert(ListNode* head, int loc,int val) {
//2种情况 1开头2中间 我的想法是占据loc位置的人的前面一个位置就行
ListNode* p = head;
ListNode* s = new ListNode(val);
ListNode* p1 = head;
while ((loc-1)) {
p1 = p;
p = p->next;
loc--;
}
if (p == head) {
head = s;
s->next = p;
}
else {
p1->next = s;
s->next = p;
}
return head;
}
ListNode * del(ListNode *head, int val) {
//2种情况,开头中间
ListNode* p = head;
ListNode* p1 = p;
while (p->val != val && p->next!=NULL) {
p1 = p;//p1永远在p前面
p = p->next;
}
if (p->val == val) {
if (p == head) {
head = p->next;
delete p;
}
else{
p1->next = p->next;
delete p;
}
}
else {
cout << "Could not found in the curret list!" << endl;
}
return head;
}
int main() {
ListNode* p = creat();
print(p);
p = del(p,2);
print(p);
cout << "the length of list is:" << length(p) << endl;
p=insert(p,2, 10);
print(p);
return 0;
}
链表配合vector
#include<iostream>
#include<stack>
#include<vector>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x):val(x),next(NULL){}
};
int main() {
ListNode* head = new ListNode(1);
ListNode* pt = head;
pt->next = new ListNode(2);
pt = pt->next;
pt->next = new ListNode(3);
pt->next->next = NULL;
pt = head;
while (pt != NULL) {
cout << pt->val << " ";
pt = pt->next;
}
cout << endl;
cout << head << endl;//打印的是头节点的地址
vector<ListNode*>A = { head };//存放的都是各节点地址
while (A.back()->next != NULL) {
A.push_back(A.back()->next);
}
cout << A[A.size() / 2] << endl;//A[A.size() / 2]->val就是输出值
}
输出:
1 2 3
005EE3D8
String
cstring和string
//字符串转字符数组
48 //不推荐的用法,但是需要了解
49 string a = "abc123";
50 const char *b;//这里必须为const char *,不能用char *,不然下一句会报错
51 b = a.c_str();
52 cout << "a:" << a << endl;
53 cout << "b:" << b << endl;
54 a = "asd456";
55 cout << "a:" << a << endl;
56 cout << "b:" << b << endl;
//推荐用法
58 string c = "abc123";
59 char *d = new char[20];
60 strcpy(d, c.c_str());//因为这里没有直接赋值,所以指针类型可以不用const char *
61 cout << "c:" << c << endl;
62 cout << "d:" << d << endl;
63 c = "asd456";
64 cout << "c:" << c << endl;
65 cout << "d:" << d << endl;
66 cout << endl;
string 转 int:
int idx=11;
std::string s = std::to_string(idx);
string 转int:
string s="123";
int a=atoi(s.c_str());
//如果string不是数字形式的则转换结果为0。
c++大小写转换
#include<iostream>
#include<cstring>
using namespace std;
int main() {
string a = "aaa";
string s = "AAA";
for (int i = 0; i < s.size(); i++) {
s[i] = tolower(s[i]);
}
for (int i = 0; i < a.size(); i++) {
a[i] = toupper(a[i]);
}
int c = 1;
}
int main() {
string s = " 1234 ";
int i = s.find_first_not_of(' '); ///返回第一个不是要找的内容的位置
auto ppp = string::npos;//无符号int型
if (i == string::npos) { return 0; }
int j = s.find_last_not_of(' ');//从后开始返回第一个不是要找的内容的位置
s = s.substr(i, j - i + 1);
int aa = 1;
}
Vector
Vector注意点
int main() {
//std::vector<std::string>b = {"4","5","6","7"};
//string d = "1";
vector<int> a = { 1,2,3,4 };
//不加& x就只是a中的每一个值的拷贝,若想改变a中值就必须&x 即x是引用
for (auto &x : a) {
x = x + 1;
}
for (auto x : a) {
cout << x << " ";
}
}
输出:
2 3 4 5
注意string类型请看
int main() {
//std::vector<std::string>b = {"4","5","6","7"};
//string d = "1";
vector<string> a = { "1","2","3" };
vector<string> b = { "123","345" };
//switch(a[0][0]) {
// case '1':cout << "1" << endl; break;
// case '2':cout << "2" << endl; break;
// default:break;
//}
cout << b[0] << endl;
cout << b[0][0] << endl;
}
输出:
123
1
所以
int main() {
//std::vector<std::string>b = {"4","5","6","7"};
//string d = "1";
vector<string> a = { "1","2","3" };
vector<string> b = { "123","345" };
//a[0]为string类型, a[0][0]才是char类型
switch(a[0][0]) {
case '1':cout << "1" << endl; break;
case '2':cout << "2" << endl; break;
default:break;
}
}
vector基本语法
#include<iostream>
#include<stack>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
void print(vector<float> a,vector<float>::iterator iter) {
for (iter = a.begin(); iter != a.end(); iter++) {
cout << *iter << " ";
}
cout << endl;
}
int main() {
vector<float> ::iterator iter;
vector<float> a = { 1,2,3,4 };
print(a, iter);
a.insert(a.begin() + 1, 10);//第二位置插入10
print(a, iter);
sort(a.begin(),a.end());//排序用到algorithm中的sort默认升序
print(a,iter);
a.erase(a.begin() + 3);//删除第三个元素
print(a, iter);
print(a,iter);
cout << a.size() << endl;//a大小
a.clear();//清空 之后size()为0;
}
vector<int> A(7,3);
//指定值初始化,ilist5被初始化为包含7个值为3的int
1.push_back 在数组的最后添加一个数据
2.pop_back 去掉数组的最后一个数据
3.at 得到编号位置的数据
4.begin 得到数组头的指针
5.end 得到数组的最后一个单元+1的指针
6.front 得到数组头的引用
7.back 得到数组的最后一个单元的引用
8.max_size 得到vector最大可以是多大
9.capacity 当前vector分配的大小
10.size 当前使用数据的大小
11.resize 改变当前使用数据的大小,如果它比当前使用的大,者填充默认值
12.reserve 改变当前vecotr所分配空间的大小
13.erase 删除指针指向的数据项
14.clear 清空当前的vector
15.rbegin 将vector反转后的开始指针返回(其实就是原来的end-1)
16.rend 将vector反转构的结束指针返回(其实就是原来的begin-1)
17.empty 判断vector是否为空
18.swap 与另一个vector交换数据
vector索引方式
#include<iostream>
#include<stack>
#include<vector>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
vector<int> a = { 1,2,3 };
cout << a[1.1] << endl;
cout << a[1.5] << endl;
cout << a[1.8] << endl;
}
输出:
2
2
2
Stack
stack用法
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
int main(){
stack <int> mystack;
mystack.empty(); //如果栈为空则返回true, 否则返回false;
mystack.size(); //返回栈中元素的个数
mystack.top(); //返回栈顶元素, 但不删除该元素
mystack.pop(); //弹出栈顶元素, 但不返回其值
mystack.push(); //将元素压入栈顶
}
Set
在set中元素都是唯一的,而且默认情况下会对元素自动进行升序排列,支持集合的交(set_intersection),差(set_difference) 并(set_union),对称差(set_symmetric_difference) 等一些集合上的操作。
基本用法
#Inclde<set>
set<int>a;
s.begin(); 返回set容器的第一个元素
s.end(); 返回set容器的最后一个元素
s.clear(); 删除set容器中的所有的元素
s.empty(); 判断set容器是否为空
s.insert(); 插入一个元素
s.erase(); 删除一个元素
s.size(); 返回当前set容器中的元素个数
set的创建
void print(set<int> a) {
//set无法用a[i]这样索引
for (set<int>::iterator it = a.begin(); it != a.end();it++) {
cout << *it<< " ";
}
cout << endl;
}
int main() {
set<int>a;
a.insert(3);
a.insert(2);
a.insert(4);
a.insert(1);
print(a);
a.erase(1);//根据元素删除
set<int > b(a); //拷贝构造创建set
set<int>c(b.begin(),b.end());//用set b初始化set c
}
输出:
1 2 3 4
2 3 4
map
基本用法
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数
void print(map<string, int>a) {
for (auto x : a) {
cout << x.first << ":" << x.second << endl;
}
}
int main() {
map<string, int> a;
a["1"] = 10;
a["2"] = 30;
a.erase("2");//键值删除,带返回值,如果刪除了會返回1,否則返回0
a.insert(pair<string,int>("4",40));//必须为pair
a.insert(map<string, int>::value_type("5", 50));
print(a);
cout << a.max_size() << endl;//返回可以容纳的最大元素个数
}
进阶
参考C++中的map。
unorder_map
基本用法
#include<unordered_map>
int main() {
unordered_map <int, int> m;
m[1] = 1;
m[4] = 4;
m[-1] = -1;
m[10] = 10;
m.count(10);//查找键为10是否存在有返回1,没有返回0。
for (auto x : m) {
cout << x.first << ":" << x.second << endl;
}
}
输出:
1:1
-1:-1
4:4
10:10
C++ algorithm库
stable_sort
以升序排序范围 [first, last) 中的元素。保证保持等价元素的顺序。
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Employee {
int age;
std::string name; // 不参与比较
};
bool operator<(const Employee &lhs, const Employee &rhs) {
return lhs.age < rhs.age;
}
int main()
{
std::vector<Employee> v = {
{108, "Zaphod"},
{32, "Arthur"},
{108, "Ford"},
};
std::stable_sort(v.begin(), v.end());
for (const auto &e : v) {
std::cout << e.age << ", " << e.name << '\n';
}
}
输出:
32, Arthur
108, Zaphod
108, Ford
lower_bound&&upper_bound
#include<algorithm>
#include<vector>
int main() {
vector<int> a = { 1,2,2,6,6,6,6,7,10 };
//功能:函数lower_bound()在first和last中的前闭后开区间进行
//二分查找返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置.
//注意:如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!
int low = lower_bound(a.begin(), a.end(), 6)-a.begin();
auto iter = lower_bound(a.begin(), a.end(), 6);
auto iter2 = a.begin();
//功能:函数upper_bound()返回的在前闭后开区间查找的关键字的上界,返回大于val的第一个元素位置
//注意:返回查找元素的最后一个可安插位置,也就是“元素值 > 查找值”
//的第一个元素的位置。同样,如果val大于数组中全部元素,返回的是last。(注意:数组下标越界)
int upp = upper_bound(a.begin(), a.end(), 5) -a.begin();
cout << low << "," << upp << endl;
cout << *iter<< endl;
}
输出:
3,3
6
此外 iter 和iter2 都是迭代器值为6和1
sort 自定义排序
using namespace std;
bool cmp(const int& a, const int& b)
{
return a > b; //从大到小排序
}
int main()
{
int a[10] = { 2, 3, 30, 305, 32, 334, 40, 47, 5, 1 };
vector<int> nums(a, a + 10);
sort(nums.begin(), nums.end(), cmp);
for (auto x : nums)
cout << x<<" ";
cout << endl;
system("pause");
return 0;
}
队列
特点:先进先出
queue<string> q;
q.push("Hello World!");
q.push("China");
cout<<q.front()<<endl;
输出:
Hello World!
queue<string> q;
q.push("Hello World!");
q.push("China");
q.pop();
cout<<q.front()<<endl;
输出:
China
queue<string> q;
cout<<q.size()<<endl;
q.push("Hello World!");
q.push("China");
cout<<q.size()<<endl;
输出:
输出两行,分别为0和2,即队列中元素的个数。
queue<string> q;
q.push("Hello World!");
q.push("China");
cout<<q.front()<<endl;
q.pop();
cout<<q.front()<<endl
输出:
分别是Hello World!和China。只有在使用了pop以后,队列中的最早进入元素才会被剔除。
queue<string> q;
q.push("Hello World!");
q.push("China");
cout<<q.back()<<endl;
输出:
返回队列中最后一个元素,也就是最晚进去的元素
输出值为China,因为它是最后进去的。这里back仅仅是返回最后一个元素,也并没有将该元素从队列剔除掉
转自:出处
unique
#include<iostream>
#include<cstring>
#include<set>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
int findDumplicateNumber(vector<int>& nums) {
if (nums.size() == 0) {
return -1;
}
}
int main() {
vector<int>a = { 1,2,3,4,5,5,6,6 };
auto b=unique(a.begin(), a.end());//b是迭代器类型,此时a已经为1,2,3,4,5,6,6,6
a.erase(unique(a.begin(), a.end()), a.end());
int c = 2;
}
对于上面的结果,我们可以看到,容器中不重复的元素都移到了前面,至于后面的元素,实际上并没有改变(这个过程只需结合debug来看即可)。
执行erase之后就返回了不重复的数组了
priority_queue
既然是队列那么先要包含头文件#include < queue >,优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的
priority_queue<int,vector<int>,less<int>>Q;//和下面的是相同的
priority_queue<int>Q;
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
int main() {
vector<int> arr = {3,7,5,8,9,1,4,6};
priority_queue<int, vector<int>, less<int>>Q;//对于基础类型 默认是大顶堆,即最大值在队头
for (int i = 0; i < 4; i++)Q.push(arr[i]);
int v = 1;
}
static修饰
修饰函数
//file1.cpp
#include <stdio.h>
extern void fun1(void);
static void fun(void)
{
printf("hello from fun.\n");
}
int main(void)
{
fun();
fun1();
return 0;
}
//file2.cpp
#include <stdio.h>
static void fun1(void)
{
printf("hello from static fun1.\n");
}
//void fun1(void)
//{
// printf("hello from static fun1.\n");
//}
如果使用static修饰fun1函数则编译不通过,去除static修饰之后则编译通过,这就是static的文件隔离作用
修饰变量
//file1.cpp
#include<stdio.h>
extern int a;
extern int b;
int main(){
b=4;
printf("%d",a);
printf("%d",b);
}
//file2.cpp
#include<stdio.h>
int a=1;
int b=2;
int c=3;
输出