我有一行任意长的整数(或浮点值),在文件中用逗号分隔:
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*的转换)优化内存利用率的方法是什么?
谢谢!
发布于 2011-07-31 22:39:58
像这样吗?
float val;
while (file >> val)
{
values[count++] = val;
char comma;
file >> comma; // skip comma
}发布于 2011-08-01 00:26:54
使用boost令牌器和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而不是数组,这通常是更好的选择。
Imho,这个代码有一些优点。迭代器有内置的eof处理,您可以很容易地展开分隔符。这是非常容易出错的(特别是当您使用一个使用异常的atof替换时)。
发布于 2011-08-02 19:46:37
我想尝试一些基于osgx关于使用scanf的建议的东西:
freopen("testcases.in", "r", stdin);
while( count < total_values)
{
scanf("%f,",&values[count]);
count++;
}https://stackoverflow.com/questions/6892784
复制相似问题