HHeLiBeXの日記 正道編

日々の記憶の記録とメモ‥

いろいろなクラスのiteratorのまとめ

C++の勉強をしていると、いろんなところにiteratorが出てきて面倒なので、先に主に使うクラスのiteraatorをまとめておく。

ソースコード

#include <iostream>
#include <string>
#include <set>
#include <map>
#include <list>
#include <vector>
#include <deque>
#include <array>

int main() {
    std::cout << "string" << std::endl;
    {
        std::string s = "hello";
        std::string::iterator i = s.begin();
        while (i != s.end()) {
            std::cout << "    " << *i++ << std::endl;
        }
    }

    std::cout << "array" << std::endl;
    {
        std::array<int, 5> a = { 1, 3, 4, 2, 5 };
        std::array<int, 5>::iterator i = a.begin();
        while (i != a.end()) {
            std::cout << "    " << *i++ << std::endl;
        }
    }

    std::cout << "set" << std::endl;
    {
        std::set<int> s = { 1, 3, 4, 2, 5 };
        std::set<int>::iterator i = s.begin();
        while (i != s.end()) {
            std::cout << "    " << *i++ << std::endl;
        }
    }

    std::cout << "map" << std::endl;
    {
        std::map<int,std::string> m;
        m.insert(std::make_pair(3, "world"));
        m.insert(std::make_pair(1, "hello"));
        m.insert(std::make_pair(4, "!!"));
        m.insert(std::make_pair(2, ","));
        std::map<int,std::string>::iterator i = m.begin();
        while (i != m.end()) {
            std::cout << "    " << i->first << "=" << i->second << std::endl;
            ++i;
        }
    }

    std::cout << "list" << std::endl;
    {
        std::list<int> l = { 1, 3, 4, 2, 5 };
        std::list<int>::iterator i = l.begin();
        while (i != l.end()) {
            std::cout << "    " << *i++ << std::endl;
        }
    }

    std::cout << "vector" << std::endl;
    {
        std::vector<int> v = { 1, 3, 4, 2, 5 };
        std::vector<int>::iterator i = v.begin();
        while (i != v.end()) {
            std::cout << "    " << *i++ << std::endl;
        }
    }

    std::cout << "deque" << std::endl;
    {
        std::deque<int> q = { 1, 3, 4, 2, 5 };
        std::deque<int>::iterator i = q.begin();
        while (i != q.end()) {
            std::cout << "    " << *i++ << std::endl;
        }
    }

    return EXIT_SUCCESS;
}

実行結果

string
    h
    e
    l
    l
    o
array
    1
    3
    4
    2
    5
set
    1
    2
    3
    4
    5
map
    1=hello
    2=,
    3=world
    4=!!
list
    1
    3
    4
    2
    5
vector
    1
    3
    4
    2
    5
deque
    1
    3
    4
    2
    5

まぁ、オチとしては、全て

auto i = obj.begin();

で済んでしまうというところか。