如何使用循环从文件中查找最大值和最小值

How to find largest and smallest value from a file using loop

我正在 运行 解决这个问题,我想从我正在阅读的文件中获取最大和最小的 id 值。该文件还包含其他信息。我能够成功识别最大值,但最小值只是被设置为读取的最后一个值,这不是文件中的最小值。这是代码

largestId = 0;
smallestId = 99999;
while(theFile >> firstName >> lastName >> id)
{
   if(id > largestId){
            largestId = id;
   }else if(id < smallestId){
            smallestId = id;
   }
}

您不检查错误状态。如果文件中没有值,情况会怎样。或者文件中只有一个值。

您使用幻数对最大值和最小值的大小做出假设。

if (theFile >> firstName >> lastName >> id)
{
    // You have at least one value it is the largest and smallest value.
    smallestId = largestId = id;


    while(theFile >> firstName >> lastName >> id)
    {
       // There is an argument that this would be better to write
       // as a function call as that would be self documenting.
       //  id = std::max(id, largestId);
       if(id > largestId){
                largestId = id;
       }
       if(id < smallestId){
                smallestId = id;
       }
    }
}
else {
    // ERROR
}

您可以通过使用算法和迭代器来实现更奇特的方法:

struct Person 
{
    std::string firstName;
    std::string lastName;
    int id;
};

std::istream& operator>>(std::istream& in, Person& person)
{
    return in >> person.firstName >> person.lastName >> person.id;
}

bool find_min_max(std::istream& in, int& min, int& max)
{
    using Iter = std::istream_iterator<Person>;
    auto a = std::minmax_element(Iter{in}, {},
        [](const auto& a, const auto& b) { return a.id < b.id; });
        
    if (a.first != Iter{}) 
    {
        min = a.first->id;
        max = a.second->id;
    }

    return a.first != Iter{};
}

https://godbolt.org/z/dY8KqzzxM