2012-11-13 34 views
2

有很多關於從int轉換爲字符串的帖子,但它們都涉及到只是打印到屏幕或使用ostringstream。有沒有一種方法來解析INT到字符串/ char *而不使用流?

我正在使用ostringstream,但我的公司不希望我使用任何流,因爲它有可怕的運行時。

我在C++文件中這樣做。

我的問題是,我要,在執行的過程中創造無數溪流,寫入緩衝區,然後內容複製到一個字符串,因爲這樣的:

ostringstream OS; 
os << "TROLOLOLOLOL"; 
std::string myStr = os.str(); 

有冗餘度它正在製作這個緩衝區,然後全部複製它。啊!

+1

你的例子沒有意義,爲什麼不只是'std :: string myStr(「TROLOLOLOL」);'?或者你想要增加一個字符串? – Praetorian

+0

一些提示在這裏:http://stackoverflow.com/questions/3799595/itoa-function-problem – PiotrNycz

+1

「可怕的運行時間」的爭論是胡說八道。我已經測試過,發現在某些場合可能會有10%的差異,如果你想要設置一個緩衝區並且不要做太過頭腦的事情。 – cHao

回答

6

在C++ 11:

string s = std::to_string(42); 

我做了基準幾個星期前,並得到了這些結果(使用鐺和的libC++隨電流的Xcode):

stringstream took 446ms 
to_string took 203ms 
c style took 170ms 

隨着以下代碼:

#include <iostream> 
#include <chrono> 
#include <sstream> 
#include <stdlib.h> 

using namespace std; 

struct Measure { 
    chrono::time_point<chrono::system_clock> _start; 
    string _name; 

    Measure(const string& name) : _name(name) { 
    _start = chrono::system_clock::now(); 
    } 

    ~Measure() { 
    cout << _name << " took " << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - _start).count() << "ms" << endl; 
    } 
}; 



int main(int argc, const char * argv[]) { 
    int n = 1000000; 
    { 
    Measure m("stringstream"); 
    for (int i = 0; i < n; ++i) { 
     stringstream ss; 
     ss << i; 
     string s = ss.str(); 
    } 
    } 
    { 
    Measure m("to_string"); 
    for (int i = 0; i < n; ++i) { 
     string s = to_string(i); 
    } 
    } 
    { 
    Measure m("c style"); 
    for (int i = 0; i < n; ++i) { 
     char buff[50]; 
     snprintf(buff, 49, "%d", i); 
     string s(buff); 
    } 
    } 
    return 0; 
} 
+0

這是一個堅實的基準標記,並且在我需要的數據集上,會產生巨大的差異。我可能最終會採用c風格的方法 – Fallenreaper

+0

你可以嘗試重新使用緩衝區,不知道是否有幫助。 –

+2

使用這個相同的基準,但在循環外部移動流創建,並說'ss.str(「」);'清除它每次迭代,我得到190ms的運行時間,而不是'to_string'的191ms。 'snprintf'在169ms時略快。 – cHao

3

在C++ 11中,您有std::to_string。雖然它可能使用引擎蓋下的stringstream技術。

+1

其實它可能使用sprintf,因爲它是根據該功能指定的。 – bames53

+0

@ bames53按盧卡斯克萊門特的基準來看似乎是這樣。 –

+0

嗯。有趣。也許這比ostringstream類更快? – Fallenreaper

0

重新使用stringstream緩衝區。請注意,這不是線程安全的。

#include <sstream> 
#include <iostream> 
#include <string> 

template<class T> 
bool str_to_type(const char *str, T &value) { 
    static std::stringstream strm; 
    if (str) { 
    strm << std::ends; 
    strm.clear(); 
    strm.setf(std::ios::boolalpha); 
    strm.seekp(0); 
    strm.seekg(0); 
    strm << str << std::ends; 
    strm >> value; 
    return !strm.fail(); 
    } 
    return false; 
} 

int main(int argc, char *argv[]) 
{ 
    int i; 
    if (!str_to_type("42", i)) 
    std::cout << "Error" << std::endl; 
    std::cout << i << std::endl; 
    return 0; 
} 
相關問題