STL Iterator – insertion iterators

介绍

C++ STL的插入迭代器只是构建一个插入迭代器,具体的插入工作是通过调用容器本身的插入函数完成的,一般会配合copy算法完成插入工作。

(1) back_inserter

Construct back insert iterator

template <class Container>
back_insert_iterator<Container> back_inserter (Container& x);

容器x必须要有push_back成员函数,如STL中的vector, deque and list

(2) inserter

Construct insert iterator

template <class Container, class Iterator>
insert_iterator<Container> inserter (Container& x, Iterator it);
  • 容器x必须要有insert成员函数,如STL中的vector, deque and list
  • it 是指向待插入目标容器x的位置的iterator

(3) front_inserter

Constructs front insert iterator

template <class Container>
front_insert_iterator<Container> front_inserter (Container& x);
  • 容器x必须要有push_front成员函数,如STL中的deque and list

Examples

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

int main(){

    vector<int> c1 = { 1, 2, 3, 4, 5};
    vector<int> c2 = {10, 20, 30, 40, 50};

    /* back_inserter */
    copy(c2.begin(), c2.end(), back_inserter(c1));
    for(auto &it: c1){
        cout << it << " ";
    }
    cout << endl;
    // Output: 1 2 3 4 5 10 20 30 40 50

    /* inserter */
    auto insert_it = c1.begin();
    // equal to insert_it = insert_it + 3
    advance(insert_it, 3);
    copy(c2.begin(), c2.end(), inserter(c1, insert_it));
    for(auto &it: c1){
        cout << it << " ";
    }
    cout << endl;
    // Output: 1 2 3 10 20 30 40 50 4 5 10 20 30 40 50

    /* inserter */
    list<char> L1 = {'a', 'b', 'c'};
    list<char> L2 = {'d', 'e', 'f'};
    copy(L2.begin(), L2.end(), front_inserter(L1));
    for(auto &it: L1){
        cout << it << " ";
    }
    cout << endl;
    // Output: f e d a b c

    return 0;
}

原文链接: https://www.cnblogs.com/lkyf/p/12809132.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    STL Iterator - insertion iterators

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/345455

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午3:15
下一篇 2023年3月2日 上午3:16

相关推荐