【发布时间】:2013-12-17 11:38:20
【问题描述】:
我正在尝试实现各种用于学习目的的数据结构和算法。
目前我正在尝试实现 Graph 类模板,但在尝试使用 STL unordered_map(以及将来的 consequently priority_queue)时遇到了问题。
目前发生的情况基本上是,由于某种原因,在尝试初始化图中的顶点映射时,模板类型不匹配。据我了解,由于我只打算使用本机 C++ 类型的键类型,只要我的值类型是指针,除了自定义顶点类的复制构造函数之外,我不需要做任何额外的工作。默认的比较器/哈希器就足够了。但事实并非如此,我收到的错误有点难以理解。
错误:
Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::unordered_map<T,graph<T>::vertex *,std::hash<int>,std::equal_to<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)
代码:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <numeric>
#include <functional>
using namespace std;
class vertex;
template <class T>
class graph {
public:
graph() { verts = unordered_map<T, vertex*>(); }
~graph() {
for each(auto v in verts)
delete(v);
delete(verts);
}
private:
unordered_map<T, vertex*> verts;
// --- Inner Classes ---
struct path {
vertex *dest;
double cost;
path(vertex *d = nullptr, double c = 0.0) : dest(d) : cost(c) {}
inline int compare(const path& p) {
auto other = p.cost;
return cost < other ? -1 :
cost > other ? 1 : 0;
}
};
struct edge {
vertex *dest;
double cost;
edge(vertex *d = nullptr, double c = 0.0) : dest(d) : cost(c) {}
};
class vertex {
public:
// Vertex relationships
T name;
vector<edge>* adj;
// Path Finding Information
double distance;
vertex *prev;
int scratch;
void reset_path_finding() {
distance = double.infinity();
prev = nullptr;
scratch = 0;
}
vertex(T name = default(T)) : name(name) : adj(new vector<edge>) :
distance(double.infinity()) : prev(nullptr) : scratch(0) {}
vertex(const vertex& v) {
name = v.name;
adj = v.adj;
distance = v.distance;
prev = v.prev;
scratch = v.scratch;
}
~vertex() { delete(adj); }
private:
};
};
int main()
{
graph<int> myGraph = graph<int>();
cout << "Press any key to continue..." << endl;
int x;
cin >> x;
return 0;
}
【问题讨论】:
-
你能指出错误所在的源代码吗?
-
顺便说一句,当您在
main函数中声明一个变量(类成员、本地或全局)时,如main函数中的本地myGraph或graph类中的verts,您不需要不必按照您的方式进行初始化。只要声明就足够了。