在Graph类中,我创建了Vertex类对象的无序映射作为键,并创建了float作为映射值。在顶点类中,我实现了一个朋友函数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;
    }
};


和图的标头:

#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);
 };


在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();
    }
    */
}


问题就在这里。我无法将hash_value函数的参数更改为非const,因为它期望const&parameter。另外,当我收到错误时必须将其添加到地图中时,以后将无法使用它:

二进制'==':找不到使用'const Vertex'类型的左操作数的运算符(或没有可接受的转换)

我尝试了不同的方法来克服此问题,但我还没有足够的经验。欢迎任何提示。

最佳答案

对于无序容器,您既需要哈希函数又需要进行相等性比较。例如。来自标准库:

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;


如您所见,它默认为std::equal_to<Vertex>,它查找operator==,但是您没有实现它。最简单的方法是添加它。

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


请注意,相等和哈希函数必须“同意”(意思是:a==b表示b==ahash(a)==hash(b)),否则最终会导致未定义的行为。

关于c++ - 遍历 vector 并添加实际上由迭代器指向的对象作为map中的键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41663180/

10-09 17:50
查看更多