Inserters for STL stack and priority_queue

后端 未结 2 1679
攒了一身酷
攒了一身酷 2020-12-17 19:49

std::vector, std::list and std::deque have std::back_inserter, and std::set has std::inserter.<

相关标签:
2条回答
  • 2020-12-17 20:00

    The other alternative (simpler) is just to use the underlying data structure (std::stack is usually implemented using std::deque) and accept that you have to use e.g. push_back() instead of push(). Saves having to code your own iterator, and doesn't particularly affect the clarity of the code. std::stack isn't your only choice for modelling the stack concept.

    0 讨论(0)
  • 2020-12-17 20:01

    You can always go your own way and implement an iterator yourself. I haven't verified this code but it should work. Emphasis on "I haven't verified."

    template <class Container>
      class push_insert_iterator:
        public iterator<output_iterator_tag,void,void,void,void>
    {
    protected:
      Container* container;
    
    public:
      typedef Container container_type;
      explicit push_insert_iterator(Container& x) : container(&x) {}
      push_insert_iterator<Container>& operator= (typename Container::const_reference value){
        container->push(value); return *this; }
      push_insert_iterator<Container>& operator* (){ return *this; }
      push_insert_iterator<Container>& operator++ (){ return *this; }
      push_insert_iterator<Container> operator++ (int){ return *this; }
    };
    

    I'd also add in the following function to help use it:

    template<typename Container>
    push_insert_iterator<Container> push_inserter(Container container){
        return push_insert_iterator<Container>(container);
    }
    
    0 讨论(0)
提交回复
热议问题