一些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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具