问题描述
我遇到了将浮点数转换为字符串的问题,其中 to_string
对我来说太慢了,因为我的数据可能涉及数百万个浮点数.
I have encountered problem of converting float to string where to_string
is too slow for me as my data might involves few millions floats.
我已经对将这些数据快速写出.
但是,在解决了这个问题之后,我很快意识到,将float转换为string会产生很大的影响.
However, after solving that problem, I soon realized that the conversion of float to string is leaving a big impact.
那么,除了使用其他非标准库之外,还有其他想法或解决方案吗?
So, is there any ideas or solution for this other than using other non standard library?
推荐答案
想到的一种优化是不直接使用to_string,它每次调用时都会创建一个新字符串.您可能最终也会复制该字符串,效率不高.
An optimization that comes in mind is to not directly use to_string, which creates a new string every time you call it.You probably end up copying that string too, which is not so efficient.
您可以做的是分配一个足够大的char缓冲区,以存储所需的所有字符串表示形式,然后使用printf
What you could do is to allocate a char buffer big enough to store all the string representations that you need, then use printf
http://www.cplusplus.com/reference/cstdio/printf/
一直重复使用相同的缓冲区.如果将浮点数的精度限制为固定的小数位数,则可以计算浮点数在数组中所代表的偏移量.
reusing the same buffer all the time.If you limit the precision of your floats to a fixed amount of decimals, you can compute the offset to which your float is represented in the array.
例如,如果我们只有一个值数组:
for example if we only had an array of values:
index = 1;
float f = value[index];
//corrresponding 6 chars float
const char* s = char_array[index*1];
//the representation will start at position 6, and it will be null terminated so you can use it as a string
为澄清起见,您的char_array如下所示:
for clarification your char_array will look like:
1.2000\02.4324\0...
这篇关于将浮点数转换为字符串的最快C ++方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!