Inserters for STL stack and priority_queue(STL 堆栈和 priority_queue 的插入器)
问题描述
std::vector
、std::list
和 std::deque
有 std::back_inserter
,并且 std::set
有 std::inserter
.
std::vector
, std::list
and std::deque
have std::back_inserter
, and std::set
has std::inserter
.
对于 std::stack
和 std::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 的插入器
基础教程推荐
- C++输入/输出运算符重载 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++按值调用 1970-01-01
- C++定义类对象 1970-01-01
- 初始化变量和赋值运算符 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- C++ #define 1970-01-01
- C语言访问数组元素 1970-01-01