STL 堆栈和 priority_queue 的插入器

Inserters for STL stack and priority_queue(STL 堆栈和 priority_queue 的插入器)

本文介绍了STL 堆栈和 priority_queue 的插入器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::vectorstd::liststd::dequestd::back_inserter,并且 std::setstd::inserter.

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

对于 std::stackstd::priority_queue 我会假设等效的插入器是 push() 但我可以似乎找不到要调用的正确函数.

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

推荐答案

你总是可以走自己的路,自己实现一个迭代器.我尚未验证此代码,但它应该可以工作.强调我还没有验证".

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

这篇关于STL 堆栈和 priority_queue 的插入器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:STL 堆栈和 priority_queue 的插入器

基础教程推荐