- ビット演算
& 対
|または
〜非
^ XOR
>>右シフト(kビットによる右シフトはa / 2のk乗に相当します)
<<左シフト (kビットによる左シフトは*(2のk乗)に相当します)
#include<iostream>
using namespace std;
int main()
{
int a = 4;
//2
cout << (a >> 1) << endl;
}
一般的な操作:
- x x >> k&1のk番目の桁を見つけます
- lowbit(x)= x&-x、次のようにx1の最後の桁を返します。100010100は100を返します
共通のライブラリ関数、
- 逆行する
①ベクトルを反転します。
#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.ユニークからヘビー
重複排除後にテールイテレータ(またはポインタ)を返します。これは、開く前にまだ閉じています。つまり、このイテレータは、重複排除後の最後の要素の次の位置です。この関数は、反復後の要素数を計算するためにイテレーター(またはポインター)減算を使用して、離散化によく使用されます。簡単に言うと、一意の関数を呼び出すと、配列が重複排除され、重複排除後に配列内の要素の数が返されます。
#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ランダムシャッフル(使用法はリバースと同じです)
#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の3番目のパラメーターは、要素xを渡し、2つのイテレーター(ポインター)で指定された部分でバイナリ検索を実行し、x以上の最初の要素の位置を指すイテレーター(ポインター)を返します。
upper_boundの使用法はlower_boundとほぼ同じですが、唯一の違いはxより大きい最初の要素を見つけることです。もちろん、2つのイテレータ(ポインタ)で指定された部分は、事前にソートする必要があります。
#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;
}