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



我遇到了这个问题,我想从我正在读取的文件中获得最大和最小的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