C++中的迭代器错误
Iterator error in C++
我正在编写一个适配器类,它为使用 set 的优先级队列提供接口。
#include<set>
using namespace std;
template<typename PRIO,typename VALUE >
class Adapter
{
//a typedef for a type "item", which acts as a pointer to an element in the queue
//(item is used below in various methods).
template<typename PR,typename VAL>
class Node{
public:
PR prio;
VAL value;
Node(PR p,VAL v) : prio(p),value(v) {}
};
set< Node<PRIO,VALUE> > queue;
public:
typedef typename set< Node<PRIO,VALUE> >::iterator item;
// inserts a new element
item insert(const PRIO &prio, const VALUE &value)
{
Node<PRIO,VALUE> temp(prio,value);
return (queue.insert(temp)).first;
}
// decreases the priority of item to prio
item decPrio(item& it, const PRIO &prio) //CHANGED !!!!
{
Node<PRIO,VALUE> temp(prio,it->value);
queue.erase(it);
it=queue.insert(temp);
}
// returns the minimum element
item findMin() const {return queue.begin();}
};
当我编译代码时,我收到错误,与运算符 = 不匹配 it
(decPrio 中的变量)。还有一些与 std::less 相关的错误。怎么了?
在这一行中:
Node<PRIO,VALUE> temp(prio,item->value);
item
是一种类型。 也许你的意思是:
Node<PRIO,VALUE> temp(prio,it->value);
std::set
需要一个比较函数对象来清除重复的对象。此函数对象作为可选的第二个模板参数传递给std::set
:
struct Foo {
int x;
};
std::set<Foo> foo_set; // <-- Error: doesn't know how to compare two MyType objects
struct FooCompare {
bool operator()( const Foo& lhs, const Foo& rhs ) const {
return lhs.x < rhs.x;
}
};
std::set<Foo, FooCompare> foo_set; // <-- Works: set uses FooCompare to compare two Foo objects
默认情况下,此比较函数对象设置为std::less
专用于集合的值类型。 std::less
依次调用operator<
集合的值类型。
struct Foo {
int x;
bool operator<( const Foo& rhs ) const {
return x < rhs.x;
}
};
std::set<Foo> foo_set; // Works!
这就是您的错误消息出现的地方。您没有为 Node
类定义operator<
,C++也无法确定您希望如何比较Node
对象。只需向Node
类添加operator<
即可解决问题。或者,您可以创建一个Node
比较函数对象,并将其作为第二个模板参数传递给您的std::set
,如上例所示。
相关文章:
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 初始化迭代器错误 C++ 在 GCC 编译器中
- 迭代器类的重载前缀增量运算符会引发分段错误
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 在静态库中使用输出迭代器时出现链接器错误
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- C++结构编译器错误询问向量的迭代器
- 编译时二叉搜索树错误的反向迭代器表示"no matching function call for operator=()"
- 编译错误 std::vector<std::shared_ptr<T>>迭代器和擦除方法
- 赛松迭代器错误
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- C++,弹出调试断言失败窗口,我得到矢量迭代器不兼容的错误运行时
- 在 leveldb 的 c++ 示例中声明迭代器时出现分段错误
- std::map 擦除 - 将迭代器传递给错误的映射
- C++向量迭代器nth_element编译错误
- 如何修复错误,迭代器未在此范围内声明,并且迭代器未命名类型'
- 如何修复使用矢量和迭代器打印值的错误
- C++ 迭代器错误"does not refer to a value"
- 使用 -std=c++0x 会导致错误:“迭代器”未命名类型错误