programmers.co.kr/learn/courses/30/lessons/42746
코딩테스트 연습 - 가장 큰 수
0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요. 예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 ��
programmers.co.kr
위 문제를 c++로 풀면서 string을 썼는데
문득 Java 를 배울때 string 을 쓰기 보다는 stringbuilder 를 쓰는게 퍼포먼스 면에서 좋다고 배웠던 기억이 났다
그러나 해당 코드를 c++로 짜는 중이었기 때문에 c++ 에 stringbuilder는 없어서 쓸 수 없었고 대신 stringstream이 비슷한 역할을 하는 것 같아서, stringstream으로 코드를 작성한뒤 성능 측정을 비교해 봤는데
//A코드 : stringstream 사용
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
bool cmp(int a, int b)
{
stringstream ss1;
stringstream ss2;
ss1 << a << b;
ss2 << b << a;
return ss1.str() > ss2.str();
}
string solution(vector<int> numbers) {
stringstream ss;
sort(numbers.begin(), numbers.end(), cmp);
for (auto& i : numbers)
{
ss << i;
}
return ss.str()[0] == '0' ? "0" : ss.str();
}
//B코드 : string만 사용
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b)
{
string s1 = to_string(a) + to_string(b);
string s2 = to_string(b) + to_string(a);
return s1 > s2;
}
string solution(vector<int> numbers) {
string answer = "";
sort(numbers.begin(), numbers.end(), cmp);
for (auto& i : numbers)
{
answer += to_string(i);
}
return answer[0] == '0' ? "0" : answer;
}
B코드, 즉 string을 사용한 쪽이 퍼포먼스가 A에 비해서 더 잘나오는것을 볼 수 있었다, 어떤 부분들은 2~3배 가까이 차이가 난다.
c++ 의 stringstream 은 Java 의 stringbuilder와 달리 퍼포먼스를 위해 쓰는 용도는 아닌것 같다,
특히나 다른 c++ 사용자들도 stringstream을 사용했을때 느리더라 라는 글들도 몇몇개 보인다.
참고 :
[퍼온글] 문자열 숫자로 바꾸기 stringstream
출처 : http://www.buggymind.com/83 요즘 C++로 Admission Control System을 개발중입니다. 근데 프로그램을 짜다 보면 으례 그렇겠지만 스트링을 숫자로, 숫자는 스트링으로 변환할 일이 많이 생기더군요. 종전
cppjava.tistory.com
'C++' 카테고리의 다른 글
template singleton (0) | 2020.07.21 |
---|---|
template _ class template, function template, explicit instantiation (0) | 2020.03.16 |
c++ typeid 연산자 (0) | 2020.03.16 |
References(L-value reference, R-value reference) (0) | 2020.03.13 |
C++ lvalue, rvalue, xvalue, glvalue, prvalue (0) | 2020.03.12 |