edo1z blog

プログラミングなどに関するブログです

C++のvector

#include <bits/stdc++.h>
using namespace std;

int main()
{
  // 1 全部0で初期化
  vector<int> v(10, 0);
  cout << "1: ";
  for(int x : v) cout << x << ' '; cout << endl;

  // 2 要素数を設定したらデフォルトでは0で初期化されるっぽい(intの場合)
  vector<int> v2(10);
  v2.push_back(10);
  cout << "2: ";
  for(int x : v2) cout << x << ' '; cout << endl;

  // 3 先頭に挿入
  v.insert(v.begin(), 3);
  v.insert(v.begin(), 2);
  v.insert(v.begin(), 1);
  cout << "3: ";
  for(int x : v) cout << x << ' '; cout << endl;

  // 4 最後尾を削除
  v.pop_back();
  cout << "4: ";
  for(int x : v) cout << x << ' '; cout << endl;

  // 5 先頭(〇番目)を削除
  v.erase(v.begin());
  cout << "5: ";
  for(int x : v) cout << x << ' '; cout << endl;

  // 6 要素の検索
  cout << "6: ";
  auto iter = find(v.begin(), v.end(), 3);
  if (iter != v.end()) {
    int idx = distance(v.begin(), iter);
    cout << "3 is v[" << idx << "]" << endl;
  } else {
    cout << "3 is not found." << endl;
  }

  // 7 ソート(小さい順)
  cout << "7: ";
  sort(v.begin(), v.end());
  for(int x : v) cout << x << ' '; cout << endl;

  // 8 ソート(大きい順)
  cout << "8: ";
  sort(v.rbegin(), v.rend());
  for(int x : v) cout << x << ' '; cout << endl;
}

結果

1: 0 0 0 0 0 0 0 0 0 0 
2: 0 0 0 0 0 0 0 0 0 0 10
3: 1 2 3 0 0 0 0 0 0 0 0 0 0
4: 1 2 3 0 0 0 0 0 0 0 0 0
5: 2 3 0 0 0 0 0 0 0 0 0
6: 3 is v[1]
7: 0 0 0 0 0 0 0 0 0 2 3
8: 3 2 0 0 0 0 0 0 0 0 0