【问题标题】:How to find largest and smallest value from a file using loop如何使用循环从文件中查找最大值和最小值
【发布时间】:2021-11-10 17:54:39
【问题描述】:

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

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

【问题讨论】:

  • 为什么要使用 else if?这两个条件不应相互依赖。
  • 你是说if(id &gt; largestId){ largestId = id;} if(id &lt; smallestId){ smallestId = id; } 不起作用?
  • 想想 id 1 和第一次迭代。它既大于largestId 又小于smallestId,但你只设置了前者。你得到最后一个数字是你特定输入的产物。
  • largestId = std::max(largestId, id);if 更清晰。

标签: c++ visual-c++ c++17


【解决方案1】:

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

您使用幻数来假设最大值和最小值的大小。

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
}

【讨论】:

  • 在这种情况下使用smallestId = largestId = id;,后面的代码可以使用if(id &lt; smallestId) --> else if(id &lt; smallestId): a micro optimization
【解决方案2】:

您可以通过使用算法和迭代器来做到这一点,这是一种更奇特的方式:

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

【讨论】:

    猜你喜欢
    • 2016-06-07
    • 2018-09-21
    • 2013-10-05
    • 2022-09-29
    • 2021-06-17
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多