【问题标题】:Defining key of map as custom struct when implementing graph in C++在 C++ 中实现图形时将映射的键定义为自定义结构
【发布时间】:2020-12-29 06:55:02
【问题描述】:

我正在学习一些图算法,并决定将图实现为邻接列表。我对 C++ 不太满意,我认为我在如何创建由地图表示的图形时犯了一些语法错误,vertex 作为键,vector<vertex> 作为值。以下所有内容都在一个文件中,此文件位于顶部:

#include <iostream>
#include <random>
#include <chrono>
#include <assert.h>
#include <algorithm>
#include <unordered_map>

using namespace std;

我意识到使用指针可能更简洁,但我现在已经承诺使用这种方法:我有一个 vertex 对象:

struct vertex
{
    int number; // unique identifier - can be 0
    int parent;
    int distance_from_root;
    char color; // one of 'w', 'b', 'g'

    bool const operator==(const int num) const // define operator for handling map with this as key
    {
        return num == number;
    }
};

我在哪里添加了operator,因为我猜C++需要一些方法来比较地图中的顶点,所以这样做map[3]应该找到3作为key.number的键我假设.我只是根据一些 SO 问题才这样做的。然后这是我尝试生成一个图(邻接表):

unordered_map<vertex, <vector<vertex>>, vertexHasher> generate_random_graph(int nv) 
{ // take as input the number of vertices in the map we're creating

    // initialize vertex objects for use in map construction later
    vector<vertex> all_vertices; 
    for (int i = 0; i < nv; ++i){ 
        vertex v; 
        v.number = i; 
        all_vertices.push_back(v);
    }
    
    // initially didn't use vertexHasher but some SO question said we need it - not sure why
    unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list; 
    for (int i = 0; i < nv; ++i){
        vector<vertex> cur_v_conns; // vertices we want our new vertex to connect to
        // create vector of vertices we want this one vertex to connect to
        int n_conns_for_cur_v = rand_int(1, 5);
        for (int j = 0; j < n_conns_for_cur_v; ++j){ 
            vertex rand_v = all_vertices[rand_int(0, all_vertices.size()-1)];
            bool exists = false; 
            for (auto conn: cur_v_conns){ // ensure we don't connect our next v to another one twice
                if (conn.number == rand_v.number) exists = true; 
            } if (!exists) cur_v_conns.push_back(rand_v); // add rand_vertex as a connection to our current it it doesn't exist
        }
        adj_list.insert({ all_vertices[i]: cur_v_conns }); // add cur_v:c cur_v_conns to map
    }
    return adj_list;
}

如果它是相关的,这里是vertexHasher(不知道为什么会出现,但是一些 SO 问题说我们需要一个自定义哈希函数?)

struct vertexHasher
{
    size_t operator()(const vertex &v) const
    {
        using std::hash;
        using std::size_t;
        using std::string;

        return ((hash<string>()(v.number) ^ (hash<string>()(v.color) << 1)) >> 1) ^ (hash<int>()(v.distance_from_root) << 1);
    }
};

我确信有几个小错误,我希望能详细说明如何解决这样的问题,这样我就可以学习一些关于 C++ 的东西,但是如果你正在寻找一个具体的问题,那么我' m 在generate_random_graph 的行上出现“预期类型标识符”错误。谢谢!你认为这是一个合理的图形解释,还是使用指针和Edge 对象的实现更好?

-- 编辑-- 这是完整的编译错误(但我怀疑除了这些表面错误之外还有更多的结构问题)

/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:101:23: error: expected expression
unordered_map<vertex, <vector<vertex>>, vertexHasher> generate_random_graph(int nv)
                      ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:101:38: error: expected '(' for function-style cast or type construction
unordered_map<vertex, <vector<vertex>>, vertexHasher> generate_random_graph(int nv)
                       ~~~~~~~~~~~~~~^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:101:39: error: expected unqualified-id
unordered_map<vertex, <vector<vertex>>, vertexHasher> generate_random_graph(int nv)
                                      ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:129:40: error: expected expression
void print_graph(unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list){
                                       ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:129:55: error: expected '(' for function-style cast or type construction
void print_graph(unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list){
                                        ~~~~~~~~~~~~~~^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:129:40: error: expected expression
void print_graph(unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list){
                                       ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:129:55: error: expected '(' for function-style cast or type construction
void print_graph(unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list){
                                        ~~~~~~~~~~~~~~^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:129:70: error: expected ')'
void print_graph(unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list){
                                                                     ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:129:17: note: to match this '('
void print_graph(unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list){
                ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:131:25: error: use of undeclared identifier 'adj_list'
    for (int i = 0; i < adj_list.size(); ++i){ // print each el in adj_list
                        ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:134:29: error: use of undeclared identifier 'adj_list'
        for (int j = 0; j < adj_list[i].size(); ++j){
                            ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:135:22: error: use of undeclared identifier 'adj_list'
            if (j == adj_list[i].size()-1){
                     ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:136:25: error: use of undeclared identifier 'adj_list'
                cout << adj_list[i][j].number << endl;
                        ^
/Users/tanishqkumar/Desktop/cs124/algs/helpers.hh:139:25: error: use of undeclared identifier 'adj_list'
                cout << adj_list[i][j].number << ", ";
                        ^
/Users/tanishqkumar/Desktop/cs124/algs/graphs.cc:11:31: error: expected expression
typedef unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list_type; 
                              ^
/Users/tanishqkumar/Desktop/cs124/algs/graphs.cc:11:46: error: expected '(' for function-style cast or type construction
typedef unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list_type; 
                               ~~~~~~~~~~~~~~^
/Users/tanishqkumar/Desktop/cs124/algs/graphs.cc:11:47: error: expected unqualified-id
typedef unordered_map<vertex, <vector<vertex>>, vertexHasher> adj_list_type;

【问题讨论】:

  • 您需要小心互换mapunordered_map。它们是非常不同的容器,对它们的密钥有不同的要求。请提供您收到的完整编译错误。将其修复为minimal reproducible example 也是一个好主意,这样我们就可以看到全貌,因为它可能与错误相关(缺少包含、使用命名空间 std 等)。
  • 尝试将&lt;vector&lt;vertex&gt;&gt; 周围多余的&lt;&gt; 删除。
  • 我做到了,这似乎使事情变得更好,但一些问题仍然存在 - 请参阅我对 Ami 回答的评论。

标签: c++ data-structures graph hashmap breadth-first-search


【解决方案1】:

这会编译并做一些事情。也许它会帮助你继续。 我已经在我必须更改的内容上添加了 cmets 以使其正常工作。

#include <iostream>
#include <random>
#include <chrono>
#include <assert.h>
#include <algorithm>
#include <unordered_map>

using namespace std;

std::random_device rd;
std::mt19937 random_generator(rd());

int rand_int(int low, int high)
{
    return std::uniform_int_distribution<int>(low, high)(random_generator);
}

struct vertex
{
    int number;
    int parent;
    int distance_from_root;
    char color; // one of 'w', 'b', 'g'

    // This needs to compare vertex with vertex, not vertex with int
    bool const operator==(const vertex& rhs) const
    {
        return number == rhs.number;
    }
};

std::ostream &operator<<(std::ostream &out, const vertex& v)
{
    out << "[ number: " << v.number << " ]";
    return out;
}

struct vertexHasher
{
    size_t operator()(const vertex &v) const
    {
        // The template parameter needs to match the type. 
        return ((hash<int>()(v.number) ^ (hash<char>()(v.color) << 1)) >> 1) ^ (hash<int>()(v.distance_from_root) << 1);
    }
};

unordered_map<vertex, vector<vertex>, vertexHasher> generate_random_graph(int nv)
{
    vector<vertex> all_vertices;
    for (int i = 0; i < nv; ++i)
    {
        vertex v;
        v.number = i;
        all_vertices.push_back(v);
    }

    unordered_map<vertex, vector<vertex>, vertexHasher> adj_list;
    for (int i = 0; i < nv; ++i)
    {
        vector<vertex> cur_v_conns;
        int n_conns_for_cur_v = rand_int(1, 5);
        for (int j = 0; j < n_conns_for_cur_v; ++j)
        {
            vertex rand_v = all_vertices[rand_int(0, all_vertices.size() - 1)];
            bool exists = false;
            // Use const reference since the object doesn't need to be modified or copied
            for (const auto& conn : cur_v_conns)
            { 
                if (conn.number == rand_v.number)
                {
                    exists = true;
                    // break since there's no reason to continue once a duplicate is found
                    break;
                }
            } 
            if (!exists)
            {
                cur_v_conns.push_back(rand_v);
            }
        }
        // Use comma, not colon
        adj_list.insert({ all_vertices[i], cur_v_conns });
    }
    return adj_list;
}

int main()
{
    auto graph = generate_random_graph(10);
    for (const auto &kvp : graph)
    {
        std::cout << "key: " << kvp.first << "\n";
        std::string delim = "values: ";
        for (const auto &v : kvp.second)
        {
            std::cout << delim << v;
            delim = ", ";
        }
        std::cout << "\n\n";
    }
}

【讨论】:

  • 您真好,谢谢。我会调查一下并回复你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多