AtcoderB問題で使えると便利なC++STLまとめ
Atcoder PloblemのA問題すべて、B問題8割程度埋め終わりましたー!
B問題を埋めていく中で、個人的によく使う便利なC++のSTL(Standard Template Library) をまとめました!!
abs
absは引数を絶対値で返してくれる関数です。
-の値と+の値の距離を求めたいときなどによく使います。
#include <iostream> #include <cmath> using namespace std; int main() { int n = -3; cout << abs(n) << endl; //出力 3 return 0; }
整数型はcmathを、小数型はcstdlibをインクルードする必要があります。
sort
配列を昇順、降順に並べたいときに多用する。
びっくりするぐらいよく使う。
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int a[5]; vector<int> v; sort(begin(a), end(a)); // 配列 sort(begin(a), end(a), greater<int>()); // 降順 sort(v.begin(), v.end()); // vector }
降順にしたい場合はgreaterを第三引数に入れるとできる。
vector
可変長配列のコンテナ。
動的に値を取得したいときに使う。
#include <iostream> #include <vector> using namespace std; int main() { int x = 0;; vector<int> v; v.push_back(x); //末尾にxを追加 v.at(1);//要素1にアクセス v.pop_back;//末尾を削除 }
min, max
変数の値の大きさを比較することができる関数。
3つ以上でも比較できてとっても便利。
cout << min(1,2) << endl; // この方式は、2つまで。 cout << min({1,2,3}) << endl; // この方式では、複数が指定できます。
substr
文字列を抜き出す関数。
#include
#include
using namespace std;
int main()
{
string s = "Atcoder";
cout << s.substr(2, 3) << endl;
//第一引数:指定する要素
//第二引数:指定した要素から何文字抜き出すか
//出力 cod
}
set
重複するデータを保持しないコンテナクラス。
同じ値を削除したいときなどに使う
#include <iostream> #include <set> using namespace std; int main() { // intをキーとして扱う集合 set<int> s; // 挿入 s.insert(3); s.insert(3); cout << s.size() << endl; //出力 1 }
multsetだと重複も追加する
reverse
名前通り、要素の並びを逆にしてくれる。
#include <algorithm> #include <iostream> #include <string> using namespace std; int main() { string str = "AtCoder"; reverse(str.begin(), str.end()); cout << str << endl; //出力 redoCtA }
reverseはO(N)かかるので計算量に注意
pow
値のべき乗を出力する
#include <iostream> #include <cmath> using namespace std; int main() { int n = 3; cout << pow(n, 2) << endl; //出力 9 }
ちなみにループのiをかけて、処理を行うことがある。
こっちの方が使いやすいときもある。
for (int i = 1; i * i < n; i++) { //処理 }
またいいのがあれば、追加します。