Vertex findMin(const list<Vertex> &adj)
{
if(adj.empty())
throw(0); // cannot find minimum of an empty list;
list<Vertex>::const_iterator bestVertex = adj.begin();
unsigned short minDistance = bestVertex->distance;
for(list<Vertex>::const_iterator itr=adj.begin(); itr!=adj.end(); ++itr)
if(itr->distance < minDistance)
{
bestVertex = itr;
minDistance = bestVertex->distance;
}
return *bestVertex;
}
how to compare lists of structures using iterator?
Question
I have a structure.
struct Vertex
{
list<Vertex> adj;
unsigned short distance; // zero or infinity
bool known;
};
I want to compare distance in the elements of list type vertex; any idea???
Vertex findMin(list<Vertex> &adj)
{
Vertex min;
for(list<Vertex>::iterator it = adj.begin(); it != adj.end(); it++){
// if(it->distance < (adj.next())->distance){
//}
return min;
}
I am using this function to return min vertex on the basis of distance property
Solution
OTHER TIPS
Use the std::min_element
algorithm. Here is pre-C++11 code:
bool isDistanceLess(const Vertex& v1, const Vertex& v2)
{ return v1.distance < v2.distance; }
Vertex findMin(const std::list<Vertex>& adj)
{ return *std::min_element(adj.begin(), adj.end(), isDistanceLess); }
Here is the C++11 version:
Vertex findMin(const std::list<Vertex>& adj)
{ return *std::min_element(adj.begin(), adj.end(), [](const Vertex& v1, const Vertex& v2) { return v1.distance < v2.distance; })); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow