LoginSignup
3
3

More than 5 years have passed since last update.

C++のVectorをint型で使ってみる。

Last updated at Posted at 2015-11-21

概要

C++のSTLで与えられるVectorの機能をまとめる。
C言語を使っている人がわかるように心がける。

Vectorってなに

VectorとはC++版、配列の動的確保と考えておけばいいと思う。
mallocと同じようなもんだ。
クラスが使えるというメリットがあるのではないだろうか。
構造体も同様に使える。
今回のようなint型の動的確保であればC言語を使っている人間はmallocで足りそうである。

ソースコードを見てみる

ソースコードを以下に示す。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> test1(5);       //int型のVectorをtest1という名前で5つ確保


    for (int i = 1; i < 6; i++)
        test1.push_back(i); //末端にiという数字を追加される

    for (int i = 0; i < 10;i++)
        cout << test1[i];   //表示をしてみる

    cout << endl;           //改行

    for (int i = 0; i < 5; i++)
        test1.pop_back();   //末端から削除される

    for (int i = 0; i < 5; i++)
        cout << test1[i];   //末端から削除されてるか確認する

    cout << endl;           //改行

    return 0;
}

ソースコード中に

cout << test1[i];
cout << endl;

と言った表記があるが、これはCの以下の様なものと理解してほしい。


printf("%d",test1[i]);
printf("\n");

概ねコメントアウトしてある。
ここでは以下の2つの関数が利用されている。

  • push_back(); 末端にデータを追加する。
  • pop_back(); 末端のデータを削除する。

動作確認

実際に実行すると

0000012345
00000
続行するには何かキーを押してください . . .

と表示することができた。
確かに末端にデータが追加され、末端からデータが削除されている。

3
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
3
3