LoginSignup
2
3

More than 5 years have passed since last update.

c++クラスまとめ ~vector編~ [随時更新中]

Last updated at Posted at 2018-06-05

vectorのよく使う用法をまとめてみた.

準備

・インクルード:#include <vector>

・宣言:vector<int> v(N,0);:Nはサイズ,全て0で初期化.

・初期化:vector<int> v{1,2,3,4};

・二次元配列の場合は vector<vector<int>> v(n, vector<int>(n));

データの追加

・末尾にデータを追加:v.push_back("hoge"):hogeを末尾に追加

・途中にデータを追加:v.insert(v.begin() + i, k);:i番目とi+1番目の位置にkを挿入

データの削除

・i番目に要素を削除:v.erase(v.begin()+i)
※erase()をすると,vectorのデータサイズが一つ減る

・重複している要素を削除:
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());

※先にソートするべし [参考:(https://qiita.com/ysk24ok/items/30ae72f4f1060b088588 )]

状態を取得

・サイズ:v.size()で配列のサイズを取得

ソート

・昇順ソート:sort(v.begin(),v.end());

・降順ソート:sort(v.begin(), v.end(), greater<int>());

要素の最大・最小

・最大:int max = *max_element(v.begin(),v.end());

・最小:int min = *min_element(v.begin(),v.end());

参考文献

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3