vector

Last-modified: 2016-03-06 (日) 15:28:26

vectorとは?

vectorは, 配列クラスです。便利な機能がたくさんあります。

#include(): Usage: (a-page-name-you-want-to-include[,title|,notitle])

超便利なので, 使ってみることを強く勧めます。

コンストラクタ

概要
  • 次のように初期化することができる。
  • sample
    #include
    using namespace std;
    int r[5];
    int main() {
        vector<int> a;                     // 空のint型の配列を生成する
        vector<int> b(5);                  // 要素数5の配列を生成する
        vector<int> c(5, 7);               // 要素数5, 初期値7の配列を生成する
        vector<int> d(c);                  // cと同一の配列を生成する
        vector<int> e(r, r + 5);           // 配列からもvectorを作ることができる
        vector<int> f(e.begin(), e.end());
        vector<int> g( { 86, 91, 20 } );
        return 0;
    }
  • また, vectorの要素にアクセスするためには次のようにすればよい。
  • sample
    #include
    #include
    using namespace std;
    int main() {
        vector<int> v(4, 5);
        printf("%d", &v[2]); // 配列と同じようにアクセスできる
    }

clear()

概要
  • vectorを空にする(要素数を0にする)ことができる。
  • 以下のコードのように記述する。
  • 計算量は O(n)
  • sample
    #include
    
    using namespace std;
    
    int main()
    {
        vector<int> v = { 23, 45, 67 }; // --> { 23, 45, 67 }
    
        v.clear();                      // --> { }
    
        return 0;
    }

front(), back()

概要
  • 先頭要素, 末尾要素を返す。
  • 以下のコードのように記述する。
  • 計算量はO(1)
  • sample
    #include
    #include
    
    using namespace std;
    
    int main()
    {
        vector<int> v = { 86, 91, 20 };
    
        printf("front = %d\n", v.front()); // --> 86
        printf("back  = %d\n", v.back());  // --> 20
    
        return 0;
    }

push_back()

概要
  • 要素を末尾に追加することができる。
  • 以下のコードのように記述する。
  • 計算量はO(1)
  • sample
    #include
    #include
    
    using namespace std;
    
    int main()
    {
        vector<int> v;
    
        v.push_back(86); // vの末尾に86を追加する --> { 86 }
        v.push_back(91); // vの末尾に91を追加する --> { 86, 91 }
        v.push_back(20); // vの末尾に20を追加する --> { 86, 91, 20 }
    
        printf("E%d%d%d is god.\n", v[0], v[1], v[2]);
    
        return 0;
    }
    
    // by square1001

pop_back()

概要
  • 末尾要素を削除することができる。
  • 以下のコードのように記述する。
  • 計算量はO(1)
  • sample
    #include
    
    using namespace std;
    
    int main()
    {
        vector<int> v = { 86, 91, 20 };
    
        v.pop_back();    // --> { 86, 91 }
        v.pop_back();    // --> { 86 }
        v.push_back(37); // --> { 86, 37 }
    
        printf("v[1] = %d\n", v[1]);
    
        return 0;
    }

size()

概要
  • vector配列の要素数を返します。
  • 以下のコードのように記述します。
  • 計算量はO(1)
  • sample
    #include
    #include
    
    using namespace std;
    
    int main()
    {
        vector<int> v =  { 86, 91, 20 };
    
        printf("%d\n", v.size()); // v = { 86, 91, 20 } なので要素数は3
    
        return 0;
    }