www.pudn.com > AdaBoost_weaklearner_1.rar > graph.cpp
// File graph.cpp Graph class template implementation file
// shinnerl@ucla.edu
#ifndef GRAPH_CPP
#define GRAPH_CPP
/*
template
void Graph::getComponent(const V& v0, set& myPiece)
{
// Find all vertices connected to v0, put them in myPiece with v0.
cerr << "\nYou must implement function Graph::getComponent()."
<< std::endl;
assert(0);
}
*/
template // Verify "undirectedness" of graph data
bool Graph::isSymmetric( pair& badEdge )
{
// The weight for edge {u,v} must be stored twice, for both (u,v) and (v,u).
// This function stops as soon as it finds one bad edge and
// passes it back, returning false. If *all* edges are ok, it returns true.
// There is no efficient way to avoid visiting every stored edge *twice*.
//
// Recall, edge (u,v) with weight w is stored in u's Adjacency map as
// the pair (v,w).
bool symmetric = true;
std::map >::iterator p;
for (p = map< V, map >::begin();
p !=map< V, map >::end();
++p)
{
const V& v_i = p->first; // shorthand
map& v_i_map = p->second; // shorthand
if (!v_i_map.empty())
{
std::map::iterator q;
for ( q = v_i_map.begin();
symmetric && q != v_i_map.end();
++q )
{
const V& neighbor = q->first;
W edgeWeight = q->second;
W* counterWeightPtr = findEdge(neighbor, v_i);
if (!counterWeightPtr || (*counterWeightPtr != edgeWeight))
{
symmetric = false;
badEdge.first = v_i;
badEdge.second = neighbor;
}
}
}
}
return symmetric;
}
template
void Graph::insertVertex( const V& v )
{
operator[](v) = map(); // Initially, v has no neighbors.
}
template
void Graph::removeVertex( const V& v )
{
// Before removing v, we must remove all edges incident upon it.
// To do this, we visit every neighbor of v and remove v from
// that neighbor's adjacency map. Then we remove v.
map *Aptr = findVertex( v );
if (Aptr) {
std::map::iterator p;
for ( p = Aptr->map::begin();
p != Aptr->map::end();
++p ) {
map *tAptr = findVertex(p->first);
tAptr->erase( v ); // tAptr nonzero if the Graph is symmetric.
}
}
map >::erase(v);
}
template // Symmetry preserving.
void Graph::removeEdge( const V& v1, const V& v2 )
{
map *A1ptr = findVertex(v1),
*A2ptr = findVertex(v2);
if (A1ptr && A2ptr)
{
if (findEdge(v1, v2))
A1ptr->erase( v2 );
if (findEdge(v2, v1))
A2ptr->erase( v1 );
}
}
template // Symmetry preserving.
void Graph::setEdge(const V& v1, const V& v2, const W& w)
{
map *A1ptr = findVertex(v1),
*A2ptr = findVertex(v2);
if (A1ptr && A2ptr)
{
A1ptr->operator[](v2) = w;
A2ptr->operator[](v1) = w;
}
}
template
map* Graph::findVertex(const V& v) const
{
map* nhbdPtr = 0;
std::map< V, map >::const_iterator p1
= map< V, map >::find(v);
if (p1 != map< V, map >::end())
nhbdPtr = const_cast