我有一个这样的大型 CSV (~75 MB):
1,3,4.1,5.4
-2,-4,-0.1,-11.3
...
我用这段代码存储我的数据(C风格):
#include <iostream>
#include <cstdio>
#include <vector>
int main()
{
int s;
int x;
float y;
double z;
std::vector<int> t;
std::vector<int> u;
std::vector<float> v;
std::vector<double> w;
if (std::FILE *f = std::fopen("data.csv", "r")) {
while (std::fscanf(f, "%d,%d,%f,%lf", &s, &x, &y, &z) == 4) {
t.push_back(s);
u.push_back(x);
v.push_back(y);
w.push_back(z);
}
std::fclose(f);
}
return 0;
}
我花了这么大的 CSV 文件(~75MB):
real 0m3.195s
user 0m3.032s
sys 0m0.148s
C 风格的速度太快了!
这段代码的另一种方式(C++风格):
#include <iostream>
#include <fstream>
#include <vector>
int main()
{
char c; // to eat the commas. Not eat spaces :-(
int s;
int x;
float y;
double z;
std::vector<int> t;
std::vector<int> u;
std::vector<float> v;
std::vector<double> w;
std::ifstream file("data.csv");
while (file >> s >> c >> x >> c >> y >> c >> z) {
t.push_back(s);
u.push_back(x);
v.push_back(y);
w.push_back(z);
}
return 0;
}
我花了这么大的 CSV 文件(~75MB):
real 0m4.766s
user 0m4.660s
sys 0m0.088s
C风格更快!
我想读取第一列(或第二列)中的字符串并放入一个向量std::string
.
我尝试了很多可能性(char *、iostream 等),但我无法以快速而优雅的方式完成。
大型 CSV 文件类型的示例(是否有一种比另一种更容易阅读?):
a.csv:
hi,3,4.1,5.4
hello,-4,-0.1,-11.3
...
b.csv:
hi 3 4.1 5.4
hello -4 -0.1 -11.3
...
c.csv:
"hi",3,4.1,5.4
"hello",-4,-0.1,-11.3
...
d.csv:
"hi" 3 4.1 5.4
"hello" -4 -0.1 -11.3
...
非常感谢你的帮助! :)