array拷贝至vector
int A[] = {1, 2, 3, 4};
int Asize = sizeof(A) / sizeof(int);
vector<int> V(A, A + Asize);
sort()函数中的cmp()
必须遵循 严格弱序
// 升序
bool cmp1(const int &a, const int &b)
{
return a < b;
}
// 降序
bool cmp2(const int &a, const int &b)
{
return a > b;
}
// 调用
int A[] = {12, 31, 2, 99, 24};
int Asize = sizeof(A) / sizeof(int);
vector<int> V(A, A + Asize);
sort(A, A + Asize, cmp1);
sort(V.begin(), V.end(), cmp2);
- 与 C C C 中的 q s o r t ( ) qsort() qsort() 比较
// 升序
int cmp3(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
// 降序
int cmp4(const void *a, const void *b)
{
return *(int*)b - *(int*)a;
}
// 调用
int A[] = {12, 31, 2, 99, 24};
int Asize = sizeof(A) / sizeof(int);
qsort(A, Asize, sizeof(int), cmp3);
qsort(A, Asize, sizeof(int), cmp4);
priority_queue中的cmp()
与 s o r t ( ) sort() sort() 正好相反
// 最大堆
struct cmp1
{
bool operator()(const int &a, const int &b)
{
return a < b;
}
};
// 最小堆
struct cmp2
{
bool operator()(const int &a, const int &b)
{
return a > b;
}
};
// 调用
int A[] = {12, 31, 2, 99, 24};
priority_queue<int, vector<int>, cmp1> Q1; // 最大堆
priority_queue<int, vector<int>, cmp2> Q2; // 最小堆
快速读取
- 整型
int quickin(void)
{
int ret = 0;
char ch;
bool flag = false;
ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
flag = true;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
ret = 10 * ret + ch - '0';
ch = getchar();
}
if (flag)
ret = -ret;
return ret;
}
- 字符串
void quickin(char *p, int *size)
{
char ch = getchar();
while (ch == ' ' || ch == '\n' || ch == '\r')
ch = getchar();
while (ch != ' ' && ch != '\n' && ch != '\r' && ch != EOF)
{
p[(*size)++] = ch;
ch = getchar();
}
}
全排列 next_permutation()
使用前要对数组按升序排序,因为该函数是按字典顺序进行判断的,随着循环的进行,字典大小逐渐变大。
#include<bits/stdc++.h>
using namespace std;
int main() {
int A[] = {1, 2, 4, 3};
sort(A, A + 4);
int ans = 0;
do
{
for (int i = 0; i < 4; i++)
cout << A[i] << ' ';
cout << endl;
ans++;
} while (next_permutation(A, A + 4));
cout << ans << endl;
return 0;
}
本文介绍了C++中sort(),qsort()函数的使用,包括自定义比较函数,以及如何在priority_queue中实现最大堆和最小堆。同时讨论了全排列next_permutation()函数的应用,强调了先排序的重要性。





