c ++在列中查找最大值和最小值

时间:2016-09-30 22:44:28

标签: c++ linux

如何从文件中的列中找到最大和最小数字?然后显示与该号码相关联的字符串? (不使用数组) 示例

column1:10 15 105 7 45
                                                                                                                                                       第2栏中的字符串:a b c d e

1 个答案:

答案 0 :(得分:1)

您只需逐行读取文件,记住最小值和最大值以及它在结束时找到的相关字符串。

#include <fstream>
#include <limits>
#include <iostream>

void printMaxAndMin() {
  std::ifstream infile("file.txt");
  int curVal, 
      maxVal = std::numeric_limits<int>::min(), 
      minVal = std::numeric_limits<int>::max();
  std::string curStr, maxStr, minStr;

  while (infile >> curVal >> curStr) {
     maxStr = maxVal < curVal ? curStr : maxStr;
     maxVal = maxVal < curVal ? curVal : maxVal;

     minStr = minVal > curVal ? curStr : minStr;
     minVal = minVal > curVal ? curVal : minVal;
  }
  std::cout << "minimum: " << minVal << ", " << minStr << std::endl;
  std::cout << "maximum: " << maxVal << ", " << maxStr << std::endl;
}