一些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\) 中的 \(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()

\(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;
}

lower_bound()和upper_bound

调用前提:有序序列

  • 升序(默认情况,用 less<int>(),可省略)
    lower_bound(first, last, value, (less<int>())):二分查找 [first, last) 中的元素,返回首个不小于 value 的元素的迭代器。
    upper_bound(first, last, value, (less<int>())):二分查找 [first, last) 中的元素,返回首个大于 value 的元素的迭代器。
  • 降序(必须用 greater<int>()
    lower_bound(first, last, value, greater<int>()):二分查找 [first, last) 中的元素,返回首个不大于 value 的元素的迭代器。
    upper_bound(first, last, value, greater<int>()):二分查找 [first, last) 中的元素,返回首个小于 value 的元素的迭代器。

set用于排除重复元素

set<int> S;        \\ 定义集合S

S.insert(1);        \\ 插入元素
...

cout << S.size() << endl;    \\ 各不相同的元素的个数

to be continued

posted @   ltign  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示