【C++】STL for TopCoder

TopCoderを始めて、最初にSTLの使い方でつまづいたので、最低限必要なものを備忘録を兼ねて簡単に解説します。 初心者向けです。

vector

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

int main() {
        /*
         * vector<>の宣言
         * 空のvector<>が作られる
         */
        vector<int> n;
        /*
         * 要素の追加
         * n.push_back(val)
         * vectorの最後尾に値が追加される
         */
        n.push_back(10);
        for (int i = 0; i < 20; i++)
        {
                n.push_back(i);
        }
        /*
         * vectorの要素数
         * n.size()
         */
        cout << n.size() << endl;
        /*
         * 要素へのアクセス
         * n.at(i)
         * nのi番目の要素が取り出される
         */
        int x = n.at(0);
        cout << x << endl;
        /*
         * 配列のような書き方も出来る(が、atの方が早いらしい)
         */
        for (int i = 1; i < n.size(); i++)
        {
                cout << n[i] << " ";
        }
        cout << endl;
}


Category読み物