12

std::vectorstd::list并且std::dequestd::back_inserter,并且std::setstd::inserter

对于std::stack并且std::priority_queue我会假设等效的插入器是 apush()但我似乎找不到要调用的正确函数。

我的意图是能够将以下函数与正确的插入迭代器一起使用:

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

2 回答 2

4

您始终可以按照自己的方式自己实现迭代器。我尚未验证此代码,但它应该可以工作。强调“我还没有验证”。

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

我还将添加以下功能来帮助使用它:

template<typename Container>
push_insert_iterator<Container> push_inserter(Container container){
    return push_insert_iterator<Container>(container);
}
于 2010-11-06T22:21:45.263 回答
4

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.

于 2010-11-07T14:06:10.887 回答