迭代器

主要记录几种未注意到的迭代器,<= C++17.

  • istream_iterator

    std::vector<int> nums = {1, 2, 3, 4};
    std::istream_iterator<int> input(std::cin);
    std::copy(input, std::istream_iterator<int>(), std::back_inserter(nums));
    
  • ostream_iterator,格式化输出数组可以简单些

    std::vector<int> nums = {1, 2, 3, 4};
    std::ostream_iterator<int> output(std::cout, " ");
    std::copy(nums.begin(), nums.end(), output);
    
  • move_iterator

    std::vector<std::string> v{"this", "_", "is", "_", "an", "_", "example"};
    std::string concat;
    for (auto begin = std::make_move_iterator(v.begin()),
        end = std::make_move_iterator(v.end());
        begin != end; ++begin)
    {
        std::string temp{*begin}; // moves the contents of *begin to temp
        concat += temp;
    }
    
  • reverse_iterator

    在cbegin()和cend()之间反向迭代,迭代器++和–操作相比正常迭代器是反向的。

    std::vector<int> v = {1, 2, 3, 4, 5};
    for (auto it = v.crbegin(); it != v.crend(); ++it)
    {
        std::cout << *it << " ";
    }
    
  • back_insert_iterator、front_insert_iterator、insert_iterator

    back_insert_iterator插入到容器的末尾,在一些algorithm库中有用,会自动调用push_back()。

    std::vector<int> v = {1, 2, 3, 4, 5};
    std::vector<int> v2 = {6, 7, 8, 9, 10};
    std::copy(v2.begin(), v2.end(), std::back_inserter(v));