简体   繁体   English

STL堆栈和priority_queue的插入器

[英]Inserters for STL stack and priority_queue

std::vector , std::list and std::deque have std::back_inserter , and std::set has std::inserter . std::vectorstd::liststd::dequestd::back_inserter ,而std::setstd::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. 对于std::stackstd::priority_queue我认为等效的插入器将是一个push()但我似乎无法找到正确的函数来调用。

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

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 eg push_back() instead of push(). 另一种选择(更简单)就是使用底层数据结构(std :: stack通常使用std :: deque实现)并接受你必须使用例如push_back()而不是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. std :: stack不是建模堆栈概念的唯一选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM