C++ 查找列中的最大和最小数

标签 c++ linux

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

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

最佳答案

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

#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;
}

关于C++ 查找列中的最大和最小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39801103/

相关文章:

Java 不能在 ubuntu 11.10 上使用 netbeans IDE 7

C - 程序仅在使用 GDB 运行时无法获取文件描述符

linux - grep,如何搜索确切的模式?

java - NDK : Pass text field value to c++ string

c++ - ROS:在 nodehandle.subscribe 中使用 lambda 作为回调

c++ - 如何在 C++ 中构建复合 for 循环?

regex - Grep 搜索特定字符问题

c++ - C++ 或库中是否有空 std::ostream 实现?

c++ - std::pair: 过于严格的构造函数?

linux - 如何多次请求一个值?