Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Data hosted with ♥ by Pastebin.com - Download Raw - See Original
- #include "stdafx.h"
- #include <iostream>
- #include <list>
- #include <queue>
- using namespace std;
- typedef list<list<int>> Graph; //define a list of list of integers as graph
- void addRib(Graph& g, int a, int b) { //function to add a rib from 'a' to 'b' to a graph
- for (Graph::iterator git = g.begin(); git != g.end(); git++) {
- if (git->front() == a) {
- git->push_back(b);
- return;
- }
- }
- list<int> vertexToAdd;
- vertexToAdd.push_back(a);
- vertexToAdd.push_back(b);
- g.push_back(vertexToAdd);
- }
- Graph::iterator point(Graph& g, int a) { //Helper function which returns an iterator, pointing to a list<int> (vertex) with first
- Graph::iterator git = g.begin(); //element 'a'. *basically returns itearator to the vertex 'a' *
- for (; git != g.end(); git++) {
- if (git->front() == a)
- return git;
- }
- return git;
- }
- bool isInList(list<int> v, int a) { //Helper function which returns whether the number 'a' is contained into the list v.
- for (list<int>::iterator vit = v.begin(); vit != v.end(); vit++) //Not really sure if std::list has it
- if (*vit == a)
- return true;
- return false;
- }
- template<typename F, typename... Targs>
- void bfsTemplate(F f, Graph& g, Targs&... args) { //The template function
- queue<int> q;
- q.push(g.front().front());
- list<int> visited;
- visited.push_back(g.front().front()); //BF traversing
- Graph::iterator currentVertex;
- while (!q.empty()) {
- currentVertex = point(g, q.front());
- if (currentVertex != g.end()) {
- visited.push_back(currentVertex->front());
- f(currentVertex, args...); //execute f with first parameter currentVertex and unknown following parameters
- for (list<int>::iterator vit = currentVertex->begin(); vit != currentVertex->end(); vit++) {
- if (!isInList(visited, *vit)) {
- q.push(*vit);
- }
- }
- }
- q.pop(); //more BF
- }
- }
- void printTest(Graph::iterator git, int& counter) { //Function to test the template
- cout << git->front() << " ";
- counter += git->front();
- }
- int main()
- {
- Graph g;
- addRib(g, 1, 2);
- addRib(g, 1, 3);
- addRib(g, 2, 5);
- addRib(g, 3, 7);
- addRib(g, 5, 7);
- addRib(g, 7, 2);
- int count = 0;
- bfsTemplate(printTest, g, count);
- return 0;
- cout << count;
- }
- //Output (1 + 2 + 3 + 5 + 7): 18
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement