简体   繁体   中英

STL store undirected graph nodes in container

I need to store unique

struct Node
    {
    int index_from;
    int index_to;
    };

in a container. Two nodes are equal under the condition

  (a.index_from==b.index_from && a.index_to==b.index_to)
||(a.index_to==b.index_from && a.index_from==b.index_to)

The Nodes need to be sorted by index_from

What container can be used for this (other than loop through array to check for existence)?

Operations: Loop though the graph from first to last according to sort key. Add unique nodes.

To sort elements of a std container with std algorithms/functions you need operator < (...), only.

Compare Nodes:

bool operator < (const Node& a, const Node& b) {
   if(a.index_from < b.index_from) return true;
   else if(a.index_from == b.index_from) {
        if(a.index_to < b.index_to) return true;
   }
   return false;
}

But it seems you want to compare the links between Nodes:

bool operator < (const Node& a, const Node& b) {
   int a0 = std::min(a.index_from, a.index_to);
   int a1 = std::max(a.index_from, a.index_to);
   int b0 = std::min(b.index_from, b.index_to);
   int b1 = std::max(b.index_from, b.index_to);
   if(a0 < b0) return true;
   else if(a0 == b0) {
        if(a1 < b1) return true;
   }
   return false;
}

Notes:

  • You might have equivalent links one pointing in the opposite direction of the other.
  • When comparing links, you might not use the operator, but a comparison object passed to the container

(insufficient rep to comment, so this is an "answer")

The "strange equality" is simply to note that the edges to/from two nodes are the same (this is an undirected graph, so there will be one edge between the nodes in question, and there is no presumption that any "direction" is inherent -- ie: given any two nodes a,b, if there are connections between a and b, then edge(a,b) is considered equal to edge(ba).)

that check for equality traps the "backwards" nodes, so those nodes don't make it into the set of valid edge descriptions, thus preserving the uniqueness constraint.

Thus, if you have nodes a,b,c & d, and you have connections between nodes a and b, b and c, and c and d and a and d, edges for (a,b); (b,c); (c,d) and (a,d) will be stored, but edges for (b,a); (c,b); (d,c) and (d,a) will be excluded.

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