1 year ago
#358416
zorka5
Why inserting into unordered_map of pair<T, T> and double always inserts into first item?
I tried to built graph class which contains of vertoces and edges. My Vertex class:
template <typename T>
class Vertex
{
private:
T data;
public:
Vertex(const T &data_) : data(data_) {}
public:
T const& get_data() const { return data; }
};
My Graph.h file:
#include <stdio.h>
#include <set>
#include <vector>
#include <unordered_map>
#include <map>
#include "Vertex.h"
struct pair_hash
{
template <class T1, class T2>
std::size_t operator() (const std::pair<T1, T2>& pair) const {
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
template <typename T>
using EdgeKey = std::pair<Vertex<T>*, Vertex<T>*>;
template <typename T>
using Edges = std::unordered_map<EdgeKey<T>, double, pair_hash>;
template <typename T>
class Graph
{
private:
std::vector <std::unique_ptr<Vertex<T>>> vertices;
Edges<T> edges;
public:
Graph(std::vector <std::unique_ptr<Vertex<T>>>&& vertices_, Edges<T> && edges_)
: vertices(std::move(vertices_)), edges(std::move(edges_)) {}
};
}
in my main.cpp file I managed to create new vertices and pass them to constructor of a Graph class:
int main()
{
std::unique_ptr<Vertex<int>> v1(new Vertex<int>(1));
std::unique_ptr<Vertex<int>> v2(new Vertex<int>(2));
std::unique_ptr<Vertex<int>> v3(new Vertex<int>(3));
std::unique_ptr<Vertex<int>> v4(new Vertex<int>(4));
std::unique_ptr<Vertex<int>> v5(new Vertex<int>(5));
std::vector<std::unique_ptr<Vertex<int>>> vertices_;
vertices_.push_back(std::move(v1));
vertices_.push_back(std::move(v2));
vertices_.push_back(std::move(v3));
vertices_.push_back(std::move(v4));
vertices_.push_back(std::move(v5));
Edges<int> edges_;
EdgeKey<int> p12(v1.get(), v2.get());
double w1 = 7.5;
EdgeKey<int> p13(v1.get(), v2.get());
double w2 = 2.5;
EdgeKey<int> p45(v4.get(), v5.get());
double w3 = 4.5;
edges_[p12] = w1;
edges_[p13] = w2;
edges_[p45] = w3;
Graph<int> G1(std::move(vertices_), std::move(edges_));
return 0;
}
But then I try to print some data about my edges, I get weird results: in main.cpp:
std::cout << vertices_.size() << std::endl;
std::cout << &p12 << " " << &p13 << " "<< &p45 << std::endl;
std::cout << edges_[p12] << std::endl;
std::cout << edges_[p13] << std::endl;
std::cout << edges_[p45] << std::endl;
std::cout << edges_.size() << std::endl;
for (auto& x : edges_) {
std::cout << ": " << x.second << std::endl;
}
5
00000008C793F028 00000008C793F078 00000008C793F0C8
4.5
4.5
4.5
1
:4.5
It seems like all new edges added to unordered map replace previously added. Am I missing something?
c++
unique-ptr
unordered-map
0 Answers
Your Answer