简体   繁体   中英

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

This is the district struct with the edge struct inside.

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

I'm attempting to create edges between vertices like this:

    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

But in order to write data to that edge, it needs to be created first with the "new" operator, as far as I understand. The districts are already initialized further up in the code to their respective places in the list array if they didn't exist there already, and I don't need help with that.

I attempted several different ways of creating a new edge:

    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;

But none of them work. How do I accomplish this?

 new district.edge 

No, district is not an object.

 new district->edge 

No, district is not a pointer.

 new edge 

No type named edge in scope. (Unless you do this inside a member function of district .)

Instead, use the scope resolution operator :: :

new district::edge

There is a new way to create district::edge in C++11:

First: get a object e of district::edge :
auto e = *(p);//p is a pointer of district::edge and it point to a real object of district::edge

Second: deduce district::edge form the object e :
using edge = decltype(e);

Now, edge is the type district::edge .

We can write code like this:
list[i]->connection[list[i]->valence] = new edge();

note: This is a common way to get unknown type in C++11.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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