DFS and BFS in a graph in C++ Here goes the depth first search:

#include &lt;vector&gt;
#include &lt;iostream&gt;

using namespace std;

typedef vector&lt;vector&lt;int&gt; &gt; graph; // adjacency list, vertexs are integers


void dfs(graph g, int s0) // s0 is the first vertex in the search
{
    int n = g.size();

    if(s0 &lt; 0 || s0 &gt;= n) // invalid initial vertex
        return;

    vector&lt;bool&gt; already_seen(n, false);
    vector&lt;int&gt; to_be_handled {};

    to_be_handled.push_back(s0);

    while(to_be_handled.size() &gt; 0)
    {
        int s = to_be_handled.back();
        to_be_handled.pop_back();

        if(!already_seen[s])
        {
            already_seen[s] = true;

            cout &lt;&lt; s &lt;&lt; " "; // handle s

            for(int v: g[s]) // add neighbors
                to_be_handled.push_back(v); // (*)
        }
    }
}


And for the breadth first search, just replace the line (*) with this line:

to_be_handled.insert(to_be_handled.begin(), v);


I guess using a queue would be more effective for the BFS but I initially just wanted to implement a DFS so don't mind the second one.
using namespace std is considered bad practice.



to_be_handled.insert(to_be_handled.begin(), v); will badly hurt the performance. As mentioned in comments, BFS benefits from using std::queue, which is specifically designed for this purpose.

Simulating stack with std::vector is also dubious, again from the performance point of view. std::vector guarantees contiguous storage, and the you'd have to face reallocation penalty as it grows. Again, std::stack is specifically designed to avoid such a penalty.



The utility of the function is severely limited by the handler being hardcoded. You may pass the handler as an argument, or better yet restructure the code to make them iterators of Graph, and let the client handle vertices, e.g.:

    Graph g;
    for (auto it: g.bfs_iterator(start)) {
        handle(it);
    }