c – STL堆栈和priority_queue的插入器
作者:互联网
std :: vector,std :: list和std :: deque有std :: back_inserter,而std :: set有std :: inserter.
对于std :: stack和std :: priority_queue,我认为等效的插入器将是一个push(),但我似乎无法找到正确的函数来调用.
我的意图是能够使用以下函数和正确的插入迭代器:
#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;
}
解决方法:
您可以随时按自己的方式自行实现迭代器.我还没有验证这段代码,但它应该可行.强调“我还没有验证”.
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);
}
标签:c,containers,stl,priority-queue,inserter 来源: https://codeday.me/bug/20191001/1838518.html