Re: Improving a short program in C++
In article <flisvl$h8a$1@aioe.org>, Rog?rio Brito <rbrito@ime.usp.br>
wrote:
<http://www.ime.usp.br/~rbrito/graphs.cpp>.
Well I would hide the new operations in the standard library containers,
for starters, Then the allocation/deallocation of heap entries becomes
automatic. Also copy constructors, assignment operators, and
destructors become easier.
for example:
typedef std::vector<int> Vertex;
class Graph
{
std::vector<Vertex> vertices;
public:
Graph(){}
explicit Graph(int n):vertices(n){}
// default copy ctor,assignment, dtor ok.
void add_arc(int v1,int v2)
{
// place v2 at the back end of vertices[v1];
vertices[v1].push_back(v2);
}
void print_graph(std::ostream &os)
{
for(int i=0;i!=vertices.size();++i)
{
os << "Vertex " << i << '\n';
for(int j=0;j!=vertices[i].size();++j)
{
os << '\t' << vertices[i][j] << '\n';
}
}
}
void add_edge(int v1,v2)
{
add_arc(v1,v2);
add_arc(v2,v1);
}
};
Bye to memory leaks!!
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]