Given a vector such as this:
struct product {
float price;
float shipping;
};
vector<product> products;
how can I remove all the products from the vector apart from the one with the largest shipping
to price
ratio?
I tried keeping an iterator to the highest one found so far...
vector<product>::iterator it = products.begin();
vector<product>::iterator largest = products.begin();
while (it != products.end())
{
if (it->shipping / it->price > largest->shipping / largest->price)
{
products.erase(largest);
largest = it;
++it;
}
else
{
it = products.erase(it);
}
}
This is all well and good but it fails if the first element in the vector has the highest ratio (it gets deleted). I could get around the problem (I think) if largest
was uninitialized and then checking for that in the if
statement, but there is no real way of doing this from what I can tell (How to check if the iterator is initialized?).
Any suggestions?