Graph Representation

I can't quite understand how does this code work as i do not really understand how to use the map and vector containers. Can anyone please help? Thank You.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    class Graph {
 protected :
 map < int , vector <int > > outgoing;

public :  
Graph( const vector < int > &startPoints , const vector < int > & endPoints); 
int numOutgoing( const int nodeID) const ; 
const vector <int > &adjacent( const int nodeID) const ; 
}; 
 
 // In a .cpp file...

 #include <stdexcept >


Graph::Graph( const vector < int > &startPoints , const vector < int > & endPoints) { 
    
    if (startPoints.size() != endPoints.size()) { 
    throw invalid_argument("Start/end point lists differ in length ");  
} 

for ( unsigned i = 0; i < startPoints . size () ; i ++ ) { 
    
    int start = startPoints [i], end = endPoints [i ]; 

outgoing [ start ]. push_back ( end ); 

outgoing [ end ]; // Just to indicate this node exists 

} }  
int Graph :: numOutgoing ( const int nodeID ) const { 
    return adjacent ( nodeID ). size () ;  
} 


const vector <int> &Graph::adjacent( const int nodeID) const {
    
    map <int , vector <int>>::const_iterator i = outgoing.find(nodeID) ; 

if (i == outgoing.end()) {  
    throw invalid_argument("Invalid node ID "); 
    } 
    return i->second; 
    }
Maybe reading the references can help?

http://www.cplusplus.com/reference/map/map/
http://www.cplusplus.com/reference/vector/vector/

A map container holds a list of pairs that have keys paired with items. The keys are used to sort and uniquely identify the items.

Vector containers are a more advanced type of array that can resize itself automatically.

Edit: I almost forgot about linking the pair reference page.
http://www.cplusplus.com/reference/utility/pair/
Pair containers have two data elements called first and second. Map containers hold a list of these pair containers.
Last edited on
Topic archived. No new replies allowed.