Simple Vertex Class
I am beginning to get back into C++ in my downtime. This is a simple Vertex class that has two members: an id, and adjacency list. The list is a multi map that contains references to the Vertex's neighbors and the weight attached to the path from the Vertex to its neighbors. The references are shared pointers since I didn't wish to deal with memory management.
Vertex header class
#ifndef __graphs__vertex__ #define __graphs__vertex__ #include <stdio.h> #include <map> #include <vector> class Vertex { char _id; std::multimap<int, std::shared_ptr<Vertex>> _adjList; public: void addNeighbor(int weight,std::shared_ptr<Vertex> neighbor); std::vector<std::pair<int,char>> getConnections(); char getId(); int getWeight(Vertex); Vertex(char); friend bool operator== (Vertex & lhs, Vertex & rhs ); }; #endif /* defined(__graphs__vertex__) */
Vertex definition class
#include "vertex.h" Vertex::Vertex(char id){ _id = id; } void Vertex::addNeighbor(int weight,std::shared_ptr<Vertex> neighbor){ _adjList.insert(std::multimap<int, std::shared_ptr<Vertex>>::value_type(weight, neighbor)); } std::vector<std::pair<int,char>> Vertex::getConnections(){ std::vector<std::pair<int,char>> ids; for(std::multimap<int, std::shared_ptr<Vertex>>::iterator it = _adjList.begin(); it != _adjList.end(); ++it) { ids.push_back(std::make_pair(it->first, it->second->_id)); }; return ids; } char Vertex::getId(){ return _id; } int Vertex::getWeight(Vertex v){ for(std::multimap<int, std::shared_ptr<Vertex>>::iterator it = _adjList.begin(); it != _adjList.end(); ++it) { if (*it->second==v) { return it->first; }; }; return -1; } bool operator== (Vertex & lhs, Vertex & rhs ){ return (lhs.getId() == rhs.getId()) ; }
Main file for example
#include <iostream> #include "vertex.h" int main(int argc, const char * argv[]) { Vertex v1('a'); v1.addNeighbor(9, std::make_shared<Vertex>('b')); v1.addNeighbor(6, std::make_shared<Vertex>('c')); for (auto i: v1.getConnections()) std::cout << i.second << ':'<< i.first <<'\n'; return 0; }