void Graph::max_path(){
for(int i=0; i <N; i++){
cost[i]=0; cam_max[i]=999;
}
// Percorre todos os vertices adjacentes do vertice
int max = 0;
list<int>::iterator i;
for (int a = 0; a < N ; a++){
int v = ordely[a];
for (i = adj[v].begin(); i != adj[v].end(); ++i){
int viz = *i;
if (cost[viz]<cost[v]+1){
cost[viz] = cost[v]+1;
if(cost[viz]>max) max = cost[viz];
}
}
}
cout << "\nCusto maximo " << max;
}
I need to convert this C++ program to a python program... However, I'm struggling to understand what this adj[v].begin() inside the for loop means. Can anyone explain it to me, please?
beginandendare iterators (specfically, pointers), which are used to iterate over a container.You could imagine
beginas0andendas thesizeof an array. So it is likefor (i = 0; i < size; ++i).However, the thing about pointers is that they're addresses, so in C++,
i < end(whereistarted asbegin) is more like0xF550 < 0xF556(example) which has the same effect of iterating 6 times assumingiincreases each iteration.In fact, that's actually how
for-eachloops work behind the scenes in many languages.In python, just use a normal for-loop.
I don't know much about python or your
Graphclass but I guess this could get you started:Notice how iterators weren't needed in the python version cause you used a normal
for-loop.By the way, in C++, you could use
for/for-eachtoo, the code you posted is unnecessarily complicated and unoptimized. For example, the first 2 loops in your code could be merged into 1 loop cause they both had the exact same range thus I optimized them into 1.