一些cpp注意事项

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;
}
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值