1.万能头文件
#include<bits/stdc++.h>
2. vector 顺序排序,逆序排序 sort函数
顺序排序为:
std::sort(v.begin(),v.end());
逆序排序为:
std::sort(v.rbegin(),v.rend());
3.getline() 读入的整个字符串包含了空格
#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
while(getline(cin, s)){
//主要逻辑
}
return 0;
}
c++中没有split方法,用下面代码可以模拟split。
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string date;
cin>>date;
stringstream ss(date);
string t;
while(getline(ss,t,'/')){
cout<<t<<endl;
}
}
/*
输入:
02/03/04
输出:
02
03
04
*/
4. 字符串读取,以“,” 作为间隔
示例:
a,c,bb
f,dddd
nowcoder
这里使用substr 函数进行分割:
string s;
vector<string> A;
vector<vector<string>> ans;
while (cin >> s) {
A.push_back(s); // 读取一行 字符串
}
for (int i = 0; i < A.size(); i++) {
int pos=0;
vector<string> res;
while (pos != -1) { // 能找到就一直迭代
pos = A[i].find(','); // 找到“,”
string temp = A[i].substr(0, pos); 分割 , 前面的字符串
res.push_back(temp);
A[i] = A[i].substr(pos + 1); // A[i] 继续迭代为,后面的字符串
}
ans.push_back(res);
}
5. 二维vector
N=2, M=2
1 1 // 代表第一行的元素
2 2 // 代表第二行的元素
int n = 0,m=0;
cout << "输入数组的行数和列数:"<<endl;
cin >> n>>m;
vector<vector<int>> A;
vector<int> temp;
int value;
for (size_t i = 0; i < n; i++) {
temp.clear(); // 用完之后 记得清空
for (size_t j = 0; j < m; j++) {
cin >> value;
temp.push_back(value);
}
A.push_back(temp);
}
输入一行数据,[[5, 4], [6, 3], [6, 7], [6, 6], [4, 6]] 这种形式的二维数组
string str;
getline(cin, str);
vector<vector<int>> A; //存放二维数组
vector<int> tem;
int value;
while (str.size() > 2)
{
int pos = str.find(']');
string temp = str.substr(2, pos - 2);
str = str.substr(pos + 2);
pos = temp.find(',');
int a = stoi(temp.substr(0, pos));
temp = temp.substr(pos + 1);
int b = stoi(temp);
tem.push_back(a);
tem.push_back(b);
A.push_back(tem);
tem.clear();
}
6.substr
substr有2种常用用法:
假设:string s = “0123456789”;
-
string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = “56789”
-
string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = “567”
7.string::npos参数——两个字符串a、b,判断a字符串是否包含b字符串
npos 是一个常数,用来表示不存在的位置
//如果字符串不存在包含关系,那么返回值就一定是npos
if(a.find(b)!=string::npos){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;