6

下面的代码显示了 2 个将 转换为 的解决方案 (std::to_string和) 。是还是更快?std::stringstreamint m_currentSoundTimestd::stringstd::to_stringstd::stringstream

// Compute current sound time in minute and convert to string
stringstream currentTime;
currentTime << m_currentSoundTime / 60;
m_currentSoundTimeInMinute =  currentTime.str();

或者

m_currentSoundTimeInMinute = to_string( m_currentSoundTime / 60 );
4

2 回答 2

7

在任何合理的库中,实现to_string至少此一样快stringstream。但是,如果您想将 10 个整数放入一个字符串中,stringstream可能会更快。如果您要执行to_string(a) + ", " + to_string(b) + /*...*/每个操作,可能会导致分配和从前一个字符串复制到新分配 - 对于stringstream.

更重要的是,从您的示例代码中可以明显看出,to_string它对于处理将单个int 转换为字符串更清晰。

于 2013-10-17T14:39:58.403 回答
4

这篇博文测试了几种整数到字符串的转换方法(在 Ubuntu 13.04 上使用 GCC 4.7)。在这种情况下to_stringstringstream. 但这可能很大程度上取决于编译器和标准库。

于 2013-10-17T14:45:05.287 回答