我試圖爲學習目的實現各種數據結構和算法。unordered_map的問題
目前我正試圖實現一個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'函數中的本地'myGraph'或'graph'類中的'verts'時,你不必初始化你做。只要宣佈它就足夠了。 –