大家好,所以我需要一个从.csv文件读入动态二维数组或向量的项目的帮助。 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];
}
答案 0 :(得分:0)
在排序时将字符串转换为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
- &gt;转化int
次。正如评论中所建议的那样,您可以使用结构。