函数整理
–最近发现之前用过的挺好用的函数有些都给忘了
–专门开一篇记录一下曾经用过的函数吧
1.C++ lower_bound( ) 与 upper_bound ( )函数
//因为是通过二分查找进行的,所以一开始要有序排序
lower_bound(val):返回容器中第一个值【大于或等于】val的元素的iterator位置。
upper_bound(val): 返回容器中第一个值【大于】val的元素的iterator位置。
temp.insert(lower_bound(temp.begin(), temp.end(), S.top()), S.top());
//insert string的插入函数
temp.erase(lower_bound(temp.begin(), temp.end(), S.top()));
//erase string的删除函数
2. C++ next_permutation( ) 函数(全排列)
由此可以看出,next_permutation(num,num+n)函数是对数组num中的前n个元素进行全排列,同时并改变num数组的值。
另外,需要强调的是,next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。比如,如果数组num初始化为2,3,1,那么输出就变为了:
2 3 1
3 1 2
3 2 1
此外,next_permutation(node,node+n,cmp)可以对结构体num按照自定义的排序方式cmp进行排序。也可以对字符排序
do {
for (int i = 0; i < n; i++)
cout << a[i];
cout << endl;
} while (next_permutation(a, a + n));
手写函数
#include<iostream>
#include<algorithm>
using namespace std;
int path[10], n;
bool vis[10];
void dfs(int cnt)
{
if (cnt == n) {
for (int i = 0; i < n; i++)
cout << path[i]<<" ";
cout << endl;
return;
}
for (int i = 1; i <= n; i++)
{
if (!vis[i])
{
vis[i] = true;
path[cnt] = i;
dfs(cnt + 1);
vis[i] = false;
}
}
}
int main()
{
cin >> n;
dfs(0);
return 0;
}
3.tolower( )和toupper( )函数(大小写字符转化)
string str = "abcABC";
for (string::iterator p = str.begin(); p < str.end(); p++)
putchar(tolower(*p));
cout << endl;
for (string::iterator p = str.begin(); p < str.end(); p++)
putchar(toupper(*p));
输出:
abcabc
ABCABC
浙公网安备 33010602011771号