将双精度转换为字符串函数-内存问题
Converting double to string function - memory issues?
我发现自己不得不std::cout各种双变量。我编写了一个简单的函数,将双精度类型转换为std::string,然后可以将其与std::cout等一起使用。
// Convert a double to a string.
std::string dtos(double x) {
std::stringstream s;
s << x;
return s.str();
}
该函数似乎可以正常工作,但我的问题是:这种方法是否有任何(坏的)内存影响。我是否分配了不必要的内存,或者留下了什么"悬空"?
谢谢皮特
不,你的代码是好的,阅读代码上的注释:
std::string dtos(double x) {
std::stringstream s; // Allocates memory on stack
s << x;
return s.str(); // returns a s.str() as a string by value
// Frees allocated memory of s
}
另外,您可以直接将double
传递给cout
令人惊讶的是没有人提到这一点,但您可以使用模板将该算法推广到任何类型。
一样:
template<typename T>
std::string to_string(const T& obj)
{
std::ostringstream s;
s << obj;
return s.str();
}
这样可以很容易地转换为字符串,如下所示:
int x = 5;
to_string(x); // will convert the integer to a string
to_string(32); // constants works
to_string<double>(302); // you can explicitly type the type you wish to convert
示例用法在此链接。
另外,正如其他人所说的,内存没有去任何地方。另外,我想提到的是,既然你只写字符串流,也许你应该使用std::ostringstream来(1)在人们阅读你的代码时进一步澄清(2)避免使用>>而不是<<
你不必改变双元组字符串使用std::cout
。
cout << x;
和
一样好cout << dtos(x);
如果你想把double类型改成string类型,你可以使用c++ 11中的std::to_string
除此之外,你的代码就很好了。
相关文章:
- C++ 中 std::vector 的内存问题
- 实现快速排序的内存问题
- 此add_node函数会导致内存问题吗?
- C++:为什么这段代码给我内存问题/未定义的行为?
- 我不明白附加字符串的内存问题
- 是否有可能存在不会崩溃程序的内存问题
- 在发布版本中删除类指针会导致内存问题
- Android OpenCV 应用程序的内存问题
- 线程的内存问题(微小线程,C++)
- 递归结构的向量有内存问题
- C++合并排序内存问题
- 将智能指针发送到Protobaf.内存问题
- 潜在的动态内存问题
- JNI 中的内存问题
- C++Lambda函数关闭-内存问题
- 解决由全局静态变量引起的内存问题
- 类堆栈内存问题(致命错误)
- QNetworkAccessManager内存问题
- 读取进程内存问题未更新
- 类指针内存问题