Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c++ - Inserters for STL stack and priority_queue

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

For std::stack and std::priority_queue I would assume the equivalent inserter would be a push() but I can't seem to find the correct function to call.

My intent is to be able to use the following function with the correct insert iterator:

#include <string>
#include <queue>
#include <iterator>

template<typename outiter>
void foo(outiter oitr)
{
   static const std::string s1 ("abcdefghji");
   static const std::string s2 ("1234567890");
   *oitr++ = s1;
   *oitr++ = s2;
}

int main()
{
   std::priority_queue<std::string> spq;
   std::stack<std::string> stk;

   foo(std::inserter(spq));
   foo(std::inserter(stk));

   return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...