一些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