- 位运算
& 与
| 或
~ 非
^ 异或
>> 右移(a右移k位相当于a / 2的k次方)
<< 左移 (a左移k位相当于a * (2的k次方))
#include<iostream>
using namespace std;
int main()
{
int a = 4;
//2
cout << (a >> 1) << endl;
}
常用操作:
- 求x的第k位数字 x >> k & 1
- lowbit(x) = x & -x,返回x的最后一位1 如:100010100 返回100
常用库函数、
- reverse 翻转
① 翻转一个vector:
#include<iostream>
#include<vector>
//algorithm为算法库
#include<algorithm>
using namespace std;
int main()
{
vector<int> a({1,2,3,4,5});
reverse(a.begin(),a.end());
for (auto x : a) cout << x << " ";
cout << endl;
}
结果如下:
② 翻转一个数组,元素存放在下标1~n:
#include<iostream>
#include<vector>
//algorithm为算法库
#include<algorithm>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5};
//reverse函数里面的两个参数分别为需要翻转的起始位置和结束位置的下一个位置
//翻转整个数组 {5,4,3,2,1}
reverse(a,a + 5);
for (auto x : a) cout << x << " ";
cout << endl;
//翻转前三个元素 {3,4,5,2,1}
reverse(a,a + 3);
for (int x : a) cout << x << " ";
cout << endl;
}
代码运行结果:
2.unique 去重
返回去重之后的尾迭代器(或指针),仍然为前闭后开,即这个迭代器是去重之后末尾元素的下一个位置。该函数常用于离散化,利用迭代器(或指针)的减法,可计算出去重后的元素个数。简单地说,调用unique函数可以对数组去重然后返回去重之后数组中的元素个数
#include<iostream>
//algorithm为算法库
#include<algorithm>
using namespace std;
int main()
{
int a[] = {1,1,2,2,3,3,4};
//对数组a去重并返回去重之后数组中的元素个数
int n = unique(a,a + 7) - a;
cout << n << endl;
//遍历数组
for (int i = 0;i < n;i++) cout << a[i] << " ";
cout << endl;
return 0;
}
运行结果:
3.random_shuffle 随机打乱(用法与reverse相同)
#include<iostream>
#include<vector>
//algorithm为算法库
#include<algorithm>
using namespace std;
int main()
{
vector<int> a({1,2,3,4,5});
//打乱vector中元素的顺序
random_shuffle(a.begin(),a.end());
for (auto x : a) cout << x << " ";
cout << endl;
return 0;
}
运行结果:
4.sort
#include<iostream>
#include<vector>
#include<ctime>
//algorithm为算法库
#include<algorithm>
using namespace std;
int main()
{
vector<int> a({1,2,3,4,5});
//设置随机种子,使每次打乱的顺序都不相同
srand(time(0));
//打乱vector中元素的顺序
random_shuffle(a.begin(),a.end());
//遍历vector
for (auto x : a) cout << x << " ";
cout << endl;
//排序,默认从小到大
sort(a.begin(),a.end());
for (auto x : a) cout << x << " ";
cout << endl;
return 0;
}
5.lower_bound/upper_bound 二分
lower_bound 的第三个参数传入一个元素x,在两个迭代器(指针)指定的部分上执行二分查找,返回指向第一个大于等于x的元素的位置的迭代器(指针)。
upper_bound 的用法和lower_bound大致相同,唯一的区别是查找第一个大于x的元素。当然,两个迭代器(指针)指定的部分应该是提前排好序的。
#include<iostream>
//algorithm为算法库
#include<algorithm>
using namespace std;
int main()
{
int a[] = {1,2,4,5,6};
//在下标0-5的范围内查找第一个大于等于3的元素 4
int *p = lower_bound(a,a + 5,3);
cout << *p << endl;
//在下标1-3的范围内查找第一个严格大于4的元素 5
int *q = upper_bound(a + 1,a + 3,4);
cout << *q << endl;
}
#include<iostream>
#include<vector>
//algorithm为算法库
#include<algorithm>
using namespace std;
int main()
{
vector<int> a = {1,2,4,5,6};
//t表示的是vector中第一个大于等于4的元素的下标
int t = lower_bound(a.begin(),a.end(),4) - a.begin();
cout << a[t] << endl;
//r表示的是vector中第一个严格大于4的元素的下标
int r = upper_bound(a.begin(),a.end(),4) - a.begin();
cout << a[r] << endl;
return 0;
}