简体   繁体   English

遍历向量并添加实际上由迭代器指向的对象作为map中的键

[英]Iterating over vector and adding object actually being pointed at by iterator as a key in map

In a Graph class I created unordered map of Vertex class objects as key and float as mapped value. 在Graph类中,我创建了Vertex类对象的无序映射作为键,并创建了float作为映射值。 In vertex class there is a friend function hash_value that I implemented in order to use custom class objects as key: http://boost.cowic.de//libs/functional/hash/examples/point.cpp . 在顶点类中,我实现了一个朋友函数hash_value,以便使用自定义类对象作为键: http : //boost.cowic.de//libs/functional/hash/examples/point.cpp

#include <string>
#include <boost/functional/hash.hpp>

class Vertex{
private:
    std::string label;
    int x;
    int y;
    int vertex_no;
    bool visited;
public:
        Vertex(std::string _label, int coordinate_x, int coordinate_y);
        void SetVertexNo(int n);
        int GetPositionX();
        int GetPositionY();
        bool GetVisited();
        void SetVisitedTrue();
        bool IsVisited();
        std::string GetLabel();

friend std::size_t hash_value(Vertex const& v) {
        std::size_t seed = 0;
        boost::hash_combine(seed, v.x);
        boost::hash_combine(seed, v.y);

        return seed;
    }
};

And header of Graph: 和Graph的标头:

#include "Vertex.h"
#include <vector>
#include <unordered_map>
#include <limits>
#include <boost/functional/hash.hpp>
#include <boost/unordered_set.hpp>
#include <boost\unordered_map.hpp>
class Graph{
    private:
        const int VERTICES_MAX = 120;
        const int VERTICES_MIN = 5;

        std::vector<Vertex> vertices_list;
        float cost_matrix[120][120];

        struct Edge { 
        std::string vertex1; std::string vertex2; float weight; };
        std::vector<Edge> edge_list;

        boost::unordered_map<Vertex, float> KEY;

    public:
        Graph(int num_of_vertices);
        float SetEdgeWeight(Vertex* v1, Vertex* v2);
        void SetGraphEdgesWeight();
        void DisplayWeightMatrix(int num_of_vertices);
        void DisplayVerticesData();
        void MatrixToEdgeList();
        void DisplayList();

        void Christofides(Graph& g);
 };

In .cpp file of Graph class I created a function that iterates over vector vertices_list and adds object actually being pointed at by iterator as the key to unordered_map 在Graph类的.cpp文件中,我创建了一个对向量vertices_list进行迭代的函数,并将迭代器实际指向的对象添加为unordered_map的键

Graph::Graph(int num_of_vertices){
    typedef boost::mt19937 RNGType; ///Mersenne twister generator
    RNGType rng(time(0));

    boost::uniform_int<> zero_to_thousand(0, 1000);
    boost::variate_generator< RNGType, boost::uniform_int<> > point(rng,  zero_to_thousand);
/*-----------------------------------------------------------------------------------*/
    for (int i = 0; i < num_of_vertices; ++i) {
        std::string vertex_label;
        std::cout << "Vertex name: " << std::endl;
        std::cin >> vertex_label;
        Vertex* V = new Vertex(vertex_label, point(), point());
        V->SetVertexNo(i);
        vertices_list.push_back(*V);

        SetGraphEdgesWeight();
        MatrixToEdgeList();
    }
}
float Graph::SetEdgeWeight(Vertex* v1, Vertex* v2) {
    int absolute_x = (v1->GetPositionX() - v2->GetPositionX());
    int absolute_y = (v1->GetPositionY() - v2->GetPositionY());
    float edge_weight = (float)(sqrt(pow(absolute_x,2)+pow(absolute_y,2)));
    return edge_weight;
}
void Graph::SetGraphEdgesWeight() {
    int i = 0;
    for (std::vector<Vertex>::iterator it = vertices_list.begin(); it !=  vertices_list.end(); ++it) {
        Vertex* pointer = &*it;
        int n = 0;
        for (std::vector<Vertex>::iterator it2 = vertices_list.begin(); it2  != vertices_list.end(); ++it2) {
            Vertex* pointee = &*it2;
            //cost_matrix[i][n] = SetEdgeWeight(pointer, pointee);
            if (pointee->IsVisited()==true) {
                cost_matrix[i][n] = cost_matrix[n][i];
            }
            else if(it == it2){
                cost_matrix[i][n] = 0;
            }
            else {
                pointer->SetVisitedTrue();
                cost_matrix[i][n] = SetEdgeWeight(pointer, pointee);
            }
            ++n;
        }
        ++i;
    }
}
void Graph::DisplayWeightMatrix(int num_of_vertices) {
    for (int i = 0; i < num_of_vertices; ++i) {
        for (int j = 0; j < num_of_vertices; ++j) {
            std::cout << "*" << " " << cost_matrix[i][j] << " ";
        }
        std::cout << "*" << std::endl;
    }
}
void Graph::DisplayVerticesData() {
    int i = 1;
    for (std::vector<Vertex>::iterator it = vertices_list.begin(); it !=   vertices_list.end(); ++it) {
        std::cout << "Vertex no: " << i << " " << "x:" << it->GetPositionX()  <<" "<< "y:" << it->GetPositionY() << std::endl;
        ++i;
    }
}
void Graph::MatrixToEdgeList() {
    int i = 0;
    for (std::vector<Vertex>::iterator it = vertices_list.begin(); it !=  vertices_list.end(); ++it) {
        int n = 0;
        for (std::vector<Vertex>::iterator it2 = vertices_list.begin(); it2 != vertices_list.end(); ++it2) {
            //std::vector<Vertex>::iterator it3 = ++it2;

            if (cost_matrix[i][n]==0) {
                 ++n;
                break;
            }
            else {
                struct Edge* e = new struct Edge;
                e->vertex1 = it->GetLabel();
                e->vertex2 = it2->GetLabel();
                e->weight = cost_matrix[i][n];
                edge_list.push_back(*e);
                ++n;
            }
        }
        ++i;
    }
}
void Graph::DisplayList() {
    for (std::vector<Edge>::iterator it = edge_list.begin(); it != edge_list.end(); ++it) {
        std::cout << "Starting vertex: " << it->vertex1 << " " << "Ending vertex: " << it->vertex2 << " " << "Edge's weight: " << it->weight<<"\n";
    }
}
void Graph::Christofides(Graph& g) {
    for (std::vector<Vertex>::iterator it = vertices_list.begin(); it != vertices_list.end(); ++it) {
        Vertex* pointer = &*it;
        g.KEY.insert(std::pair<Vertex,float>(*pointer,   std::numeric_limits<float>::max()));
        //KEY.emplace(*pointer, std::numeric_limits<float>::max());
    }


    /*
    for (auto v : g.vertices_list) {

        //KEY.insert(*v_pointer, std::numeric_limits<float>::max());
        //KEY.insert(std::make_pair(v, std::numeric_limits<float>::max()));
       //KEY[v] = std::numeric_limits<float>::max();
    }
    */
}

And here lies the problem. 问题就在这里。 I cannot change parameter of hash_value function to non-const as it expects const& parameter. 我无法将hash_value函数的参数更改为非const,因为它期望const&parameter。 Also it cannot be used later when I have to add it into a map as I get the error: 另外,当我不得不将其添加到地图中时,由于出现错误,以后无法使用它:

binary '==': no operator found which takes a left-hand operand of type 'const Vertex'(or there is no acceptable conversion) 二进制'==':未找到采用'const Vertex'类型的左操作数的运算符(或没有可接受的转换)

I tried different soultions to overcome this but I'm not enough exprienced to do so. 我尝试了不同的方法来克服此问题,但我还没有足够的经验。 Any hints are welcome. 欢迎任何提示。

For unordered containers you need both a hash function AND an equality comparison. 对于无序容器,您既需要哈希函数又需要进行相等性比较。 Eg from standard library: 例如来自标准库:

template<
    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;

As you can see it defaults to std::equal_to<Vertex> , which looks for operator== , but you didn't implement that. 如您所见,它默认为std::equal_to<Vertex> ,它查找operator== ,但是您没有实现它。 The easiest thing would be to add it. 最简单的方法是添加它。

   bool operator==(Vertex const& other) const {
        return std::tie(x,y) == std::tie(other.x, other.y);
   }

Note that the equality and hash functions must "agree" (meaning: a==b implies b==a and hash(a)==hash(b) ) or you end up with undefined behaviour. 请注意,相等和哈希函数必须“同意”(意思是: a==b意味着b==ahash(a)==hash(b) ),否则您最终将获得未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM