我遇到了這個問題,我想從一個正在讀取的檔案中獲得最大和最小的id值。這個檔案還包含其他資訊。我成功地確定了最大的值,但最小的值只是被設定為被讀取的最后一個值,而這并不是檔案中最小的值。以下是代碼
largestId = 0;
smallestId = 99999;
while(theFile >> firstName >> lastName > id)
{
if(id > largestId){
largestId = id。
}else if(id < smallestId){
smallestId = id。
}
uj5u.com熱心網友回復:
你沒有檢查錯誤狀態。那么在檔案中沒有值的情況下怎么辦?或者檔案中只有一個值。
你對檔案中的值進行了假設。
你通過使用神奇的數字對最大和最小的值的大小進行了假設。
if (theFile >> firstName >> lastName >> id)
{
//你至少有一個值它是最大和最小的值。
smallestId = largestId = id;
while(theFile >> firstName >> lastName >> id)
{
//有一種說法認為這樣寫會更好。
//作為一個函式呼叫,因為這將是自我檔案化的。
//id=std::max(id, largestId);
if(id > largestId){
largestId = id。
}
if(id < smallestId){
smallestId = id。
}
}
}
else {
// ERROR ?
}
uj5u.com熱心網友回復:
下面是你可以通過使用演算法和迭代器來實作的更花哨的方法:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/306745.html
標籤:
下一篇:在C 中對陣列進行從大到小的排序
