C++常用操作

记录备查

C++

  • 从字符串中删除子串
1
2
3
4
5
void removeSubstrs(string& s, const string& e){
int n = e.length();
for(string::size_type i = s.find(e); i != string::npos; i = s.find(e))
s.erase(i, n);
}
  • 使用STL库实现小顶堆
1
priority_queue <int, vector<int>, greater<int> > pq;
  • 自定义排序
1
2
3
4
5
6
7
struct Edge{
int x, y, len;
Edge(int x, int y, int len) : x(x), y(y), len(len){}
};

vector<Edge> edges;
sort(edges.begin(), edges.end(), [](Edge a, Edge b) -> int {return a.len < b.len;});
  • 初始化二维vector
1
2
int row = 3, col = 3;
vector<vector<int>> matrix(row, vector<int>(col, 0));
  • 位运算
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//求二进制中1的个数
int count = 0;
while(n != 0){
n &= n-1;
count++;
}
//除2
x >>= 1;
//乘2
x <<= 1;
//大写转小写
ch |= ' ';
//小写转大写
ch &= '_';
//第i位是否为1
(val >> i) & 1;
  • 分割字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//完全分割
void split(const string& s, vector<string>& record, const char delim = '.') {
record.clear();
istringstream is(s);
string temp;
while (getline(is, temp, delim)) {
record.push_back(move(temp));
}
}
//只分割一次
void split(const string& s, vector<string>& record, const char delim = '.') {
//s="www.bithub00.com"➡"bithub00.com"、"com"
record.clear();
int index = s.find('.');
while(index > 0){
string t = s.substr(index+1);
record.push_back(t);
}
}
  • 从句子中读取单词
1
2
3
4
5
6
7
string A = "Data Mining";
istringstream in(A);
vector<string> v;
string t;
while(in >> t){
v.push_back(t);
}
  • 求文件行数
1
2
3
4
5
6
7
8
9
10
int length(char *File) {
ifstream myfile(File);
string line;
int lineNum = 0;
while (getline(myfile, line))
lineNum++;
myfile.clear();
myfile.seekg(0, ios::beg); //回到文件第一行
return lineNum;
}
  • 循环查找子串出现的所有位置
1
2
3
4
5
6
7
int pos = 0;
string str;
string substr;
while(pos != string::npos) {
pos = str.find(substr, pos);
pos++;
}
  • 二分区间查找
1
2
3
4
5
6
7
8
9
10
11
12
int left = 0, right = arr.size()-1;
while(left <= right) {
int mid = left + (right-left)/2;
if(arr[mid] > value) right = mid-1;
else if(arr[mid] < value) left = mid+1;
else {
right = mid;
break;
}
}
//此时arr[right]就是arr中小于等于value的最大数
return arr[right];