我有一个任意长的整数行(或浮点值),用逗号分隔在文件中:
1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,9,3,... (can go upto >100 MB)
现在,我必须读取这些值并将它们存储在一个数组中。
我目前的实现如下:
float* read_line(int dimension)
{
float *values = new float[dimension*dimension]; // a line will have dimension^2 values
std::string line;
char *token = NULL, *buffer = NULL, *tmp = NULL;
int count = 0;
getline(file, line);
buffer = new char[line.length() + 1];
strcpy(buffer, line.c_str());
for( token = strtok(buffer, ","); token != NULL; token = strtok(NULL, ","), count++ )
{
values[count] = strtod(token, &tmp);
}
delete buffer;
return values;
}
我不喜欢这种实现,因为:
ifstream
将整个文件加载到内存中,然后
然后被克隆到float []
std::string
转换为const char*
)有哪些方法可以优化内存利用率?
谢谢!
答案 0 :(得分:4)
这样的东西?
float val;
while (file >> val)
{
values[count++] = val;
char comma;
file >> comma; // skip comma
}
答案 1 :(得分:1)
使用boost tokenizer和istreambuf_iterator
:
std::vector<float> test; //Optionally call reserve to avoid frequent memory reallocation
boost::tokenizer<boost::char_separator<char>, std::istreambuf_iterator<char> > tokens(std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>(), boost::char_separator<char>(","));
//Replace this lambda by your favourite conversion function.
std::transform(tokens.begin(), tokens.end(), std::back_inserter(test), [](std::basic_string<char> s) { return atof(s.c_str()); } );
编辑:test
是我用于values
的内容,除了std::vector
而不是数组,这通常是更好的选择。
答案 2 :(得分:0)
我想根据osgx建议使用scanf来尝试一些东西:
freopen("testcases.in", "r", stdin);
while( count < total_values)
{
scanf("%f,",&values[count]);
count++;
}