c++ - 读取 txt 文件并从第二列中找到第一列给定值的最小值

标签 c++

我有一个数据文件,其中第一列在 -180 到 +180 之间变化,宽度为 5,而第二列是一些对应的值。我需要从第二列中找到第一个对应值 -180 的最小值,打印出来,然后从第二列中找到 -175 的最小值打印出来等等......当我只有一列时,我有找到最小值的代码.我如何包含这个循环

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main()
{
    ifstream myfile("ma3.txt");
    if(myfile.is_open())
    {       
      int arrSize=0.0;
      double arr[2000];
      double min=0;

      while(true)
      {
         double x,y;
         myfile>>x;
         if(myfile.eof()) break;
         arr[arrSize++]=x;        
      }
      //for(int i=0; i<arrSize; ++i)
      //   cout<<arr[i]<<"";
      //cout<<endl;

      min=arr[0];
      for(int i=0;i<arrSize;i++)
      {
         {          
             if(arr[i]<min)
             {
                min=arr[i];
             }
         }
      }

      cout<<"Smallest element:";
      cout<<min;
      cout<<endl;
    }
    else
    {
       cout<<"Unable to open file";
    }

    return 0;
} 

输入数据:

-180 431.845 
-180 434.337 
-180 436.819 
-180 439.289 
-180 469.936 
-180 472.152 
-180 474.343 
-180 476.509 
-180 478.649 
-180 480.761 
-180 482.846 
-180 484.902 
-180 486.929 
-180 488.926
-175 387.566 
-175 384.891 
-175 382.216 
-175 379.541 
-175 376.868 
-175 374.197 
-175 371.53 
-175 368.867 
-175 366.209 
-175 363.557 
-175 360.912 
-175 358.275 
-175 355.648 
-175 353.03 
-175 350.422 
-175 347.826 
-175 345.243 
-175 342.673 
-175 340.117 
-175 337.576 
-175 335.05 
-175 332.541 
-175 330.05 
-175 327.576

最佳答案

使用关联容器跟踪多个最小值。例如订购 std::map<int, double>这个任务似乎很方便:

解决方案的一般结构如下所示:

#include <iostream>
#include <map>
int main() {
    std::map<int, double> mins;
    int x1;
    double x2;
    // TODO: read from file instead
    // TODO: read lines using `std::getline()` 
    //       and parse values using `std::stringstream` instead
    while (std::cin >> x1 >> x2) {
        // check if x1 is already being tracked
        if (mins.find(x1) != mins.end()) {
            // unknown key: just insert current value
            mins[x1] = x2;
        }
        else {
            // TODO: update value as needed
        }
    }
    // TODO: print key-value pairs in map
}

供引用:

关于c++ - 读取 txt 文件并从第二列中找到第一列给定值的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49665828/

相关文章:

c++ - Qmake错误: Unknown module(s) in QT: charts

C++ 在 while 循环后 map 的大小仍然是 1

c++ - 我试图想出一个跨平台的替代方法来替代 sleep(),但我的代码不太好用

c++ - 在宏中加入前 n-1 个参数

c++ - 从文本文件读取数据并将数据插入数组

c++ - SFML 2.0 中需要的警告框功能

javascript - 浏览器中的mp3流解码

c++ - 编译 wxLua(跨平台&静态)

c++ - 寻找fat32源

c++ - 关联两个独立的键