繁体   English   中英

尝试初始化区结构内的边结构。 我怎么做?

[英]Trying to initialize an edge struct which is inside the district struct. How do I do that?

这是带有edge结构的区域结构。

    /**
 * district struct that keeps track of the name, valence, and connections a district has to others
 */
struct district {
    /**
     * contains an edge with two vertices
     */
    struct edge {
        district *vertex1, *vertex2;
        /**
         * initializes both vertices to nullptr
         */
        edge() :
                vertex1(nullptr), vertex2(nullptr) {
        }
    };
    T name;
    int valence;
    edge *connection[100];
    int color;
    /**
     * initializes all struct members to default values
     */
    district(T name) :
            name(name), valence(0), connection { nullptr }, color(100) {
    }
};

我试图在顶点之间创建边缘,如下所示:

    list[i]->connection[list[i]->valence]->vertex1 = list[i];
    list[i]->connection[list[i]->valence]->vertex2 = list[j];
    list[i]->valence++; //add 1 to the amount of vertices for district a
    list[j]->connection[list[j]->valence]->vertex1 = list[j];
    list[j]->connection[list[j]->valence]->vertex2 = list[i];
    list[j]->valence++; //add 1 to the amount of vertices for district b
    sort(); //sort the list in order of valence

但是为了将数据写入该边缘,据我所知,需要首先使用“new”运算符创建数据。 如果区域已经存在,那么区域已经在代码中进一步初始化到列表数组中它们各自的位置,并且我不需要帮助。

我尝试了几种创建新边缘的不同方法:

    list[i]->connection[list[i]->valence] = new district.edge;
    list[i]->connection[list[i]->valence] = new district->edge;
    list[i]->connection[list[i]->valence] = new edge;

但它们都不起作用。 我该如何做到这一点?

 new district.edge 

不, district不是一个对象。

 new district->edge 

不, district不是指针。

 new edge 

范围中没有名为edge类型。 (除非你在district的成员函数内执行此操作。)

相反,使用范围解析运算符::

new district::edge

有一种在C ++ 11中创建district::edge的新方法:

首先:获取一个对象edistrict::edge
auto e = *(p);//p is a pointer of district::edge and it point to a real object of district::edge

第二:推导出section district::edge形成对象e
using edge = decltype(e);

现在, edge是type district::edge类型。

我们可以写这样的代码:
list[i]->connection[list[i]->valence] = new edge();

注意:这是在C ++ 11中获取未知类型的常用方法。

暂无
暂无

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

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