[英]Reading and sorting from CSV file C++
大家好,我需要從.csv文件讀取到動態2d數組或向量中的項目上的幫助。 CSV文件包含游泳比賽的詳細信息,我應該同時讀取名稱時間和距離以及不同的距離和時間。 然后,我需要使用時間和距離對它們進行排序,並且用戶應該能夠基於距離搜索種族,並且應該向他/她顯示某個距離內最快的時間。 這是我的代碼,它不按時間對值進行排序,因為盡管我嘗試將其轉換為int,但它仍為字符串格式。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;
bool sortByTime(const vector<int>& v1,const vector<int>& v2 );
int main(){
vector< vector<string> > heatLevels;
ifstream in("code.csv");
if(!in)
cout<< "File not found"<< endl;
string line,sector;
vector<string> v;
while(getline(in,line)){
v.clear();
stringstream ss(line);
while (getline(ss,sector,',')) // break line into comma delimited sectors
{
v.push_back(sector); // add each sector to the 1D array
}
heatLevels.push_back(v); // add the 1D array to the 2D array
}
for(int i = 0; i< heatLevels.size(); i++)
{
for(int j = 0; j<heatLevels[i].size(); j++)
{
cout<<heatLevels[i][j]<< setw(12);
}
cout<< "\n";
}
for(int i = 1; i< heatLevels.size(); i++)
{
int j=5;
stringstream converter(heatLevels[i][j]);
float x =0.0;
converter >> x;
}
//Sort table by time
sort(heatLevels.begin()+1, heatLevels.end(),sortByTime);
}
bool sortByTime(const vector<int>& a,const vector<int>& b )
{
return a[5] < b[5];
}
在排序時將字符串轉換為int
或double
。 您還可以使用lambda函數來簡化此操作:
int main()
{
vector<vector<string>> heatLevels;
ifstream in("code.csv");
if(!in)
cout << "File not found" << endl;
string line, sector;
while(getline(in, line))
{
vector<string> v;
stringstream ss(line);
while(getline(ss, sector, ','))
v.push_back(sector);
heatLevels.push_back(v);
}
for(auto &row : heatLevels)
{
for(auto &e : row)
cout << e << ",";
cout << "\n";
}
auto sortproc = [](const vector<string> &a, const vector<string> & b)
{
double ia, ib;
try
{
ia = std::stod(a[5]);
ib = std::stod(b[5]);
}
catch(...)
{
cout << "invalid or out of range\n";
return false;
}
return ia < ib;
};
std::sort(heatLevels.begin(), heatLevels.end(), sortproc);
cout << "sorted:\n";
for(auto &row : heatLevels)
{
for(auto &e : row)
cout << e << ",";
cout << "\n";
}
return 0;
}
上面的方法足夠快,但是它不是最有效的方法,因為您進行了大量的string
> int
轉換。 如注釋中所建議,您可以改用結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.