정수형을 문자열로 변환할 때의 차이점

조회수 5288회

정수형을 문자열로 바꾸는 방법엔 흔히 알기로 itoa()함수를 사용합니다.

최근에 찾아본 #include 를 따르면,

string convertInt(int number)
{
   stringstream ss;//create a stringstream
   ss << number;//add number to the stream
   return ss.str();//return a string with the contents of the stream
}

위와 같은 방식으로 int <-> string 변환을 하게 되는데, itoa()를 사용 하는 것보다 간편하다고 느껴집니다.

성능 면에서 itoa() 와 stringstream을 사용 하는 것, 둘 중 어느 것이 더 좋고 그 이유가 뭔가요?

2 답변

  • http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html 에 보니까 10,000,000개의 정수를 string으로 바꾼 실험이 있네요.

    결과는 이렇답니다.

    Method Time, s Time ratio
    fmt::FormatInt 0.140499 1
    cppx::decimal_from 0.160447 1.14197965822
    fmt::Writer 0.170481 1.21339653663
    karma::generate 0.217157 1.54561242429
    strtk::type_to_string 0.381777 2.71729336152
    karma::generate+std::string 0.405444 2.88574295902
    fmt::Writer+std::string 0.414739 2.95190001352
    fmt::format 0.443754 3.15841393889
    ltoa 0.538002 3.82922298379
    fmt::format+std::string 0.686678 4.88742268628
    sprintf 0.948262 6.74924376686
    boost::lexical_cast 1.08146 7.69727898419
    sprintf+std::string 1.20853 8.60169823273
    std::stringstream 1.42531 10.1446273639
    std::to_string 1.5242 10.8484757899
    boost::format 4.43679 31.5788012726
  • itoa는 비표준 함수이기 때문에 사용하지 않는 것이 좋습니다. 대신 다음과 같은 방법으로 정수형을 문자열로 변환하시면 됩니다.

    • C++ 11
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    string StringFromNumber(const int value) {
        return to_string(value);
    }
    
    int main(void) {
        cout << StringFromNumber(10) << endl;
    }
    
    • C++ 0x
    #include <sstream>
    #include <iostream>
    
    using namespace std;
    
    string StringFromNumber(const int value) {
      stringstream ss;
      ss << value;
      return ss.str();
    }
    
    int main(void) {
      cout << StringFromNumber(10) << endl;
    }
    
    • Boost Library 사용
    #include <iostream>
    #include <boost/lexical_cast.hpp>
    
    using namespace std;
    
    string StringFromNumber(const int value) {
          return boost::lexical_cast<string>(value);
    }
    
    int main(void) {
        cout << StringFromNumber(10) << endl;
    }
    

    이 중에서는 Boost library를 사용하는게 가장 빠르다고 하네요.

    http://stackoverflow.com/questions/23437778/comparing-3-modern-c-ways-to-convert-integral-values-to-strings

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)