본문 바로가기
Practice & Study/프로그래머스

프로그래머스>코딩테스트 입문>특정 문자 제거하기 (C++) | 문자열과 문자, remove(), erase()

문자열과 문자를 확실히 구분해야하는 문제다. 혼동하기 은근히 쉬움...

 

나의 코드

#include <string>
#include <vector>

using namespace std;

string solution(string my_string, string letter) {
    char c = letter[0];
    string str = "";

    for(int i = 0; i < my_string.length(); i++) {
        if(my_string[i] != c) {
            str.push_back(my_string[i]);
        }
    }
    return str;
}

letter가 한 글자인 스트링이어서 문자형으로 받아줬다.

굳이 그럴 필요없이 if문 안에서 바로 letter[0]으로 써도 됐을텐데... 

 

 

다른 사람의 코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(string my_string, string letter) {

    my_string.erase(remove(my_string.begin(),my_string.end(), letter[0]),my_string.end());
    return my_string;
}

algorithm 라이브러리에 있는 

 

remove(시작 반복자, 종료 반복자, 삭제할 원소 값) : 데이터는 지워지지만 공간은 남아있다. 데이터 삭제가 끝나면 해당 string의 마지막을 가리키며 반환된다. 

 

erase(시작 반복자, 종료 반복자) : 잉여 공간까지 완전히 지운다. 

 

특정 원소를 완전히 삭제하려면 erase와 remove를 함께 쓰는 것이 좋다. 

 

 

https://novemberfirst.tistory.com/111

 

[STL] erase와 remove의 차이

erase와 remove의 차이 erase, remove 한줄로 간단하게 말하자면 erase는 멤버함수이고 remove는 알고리즘이다. ◎ erase 컨테이너의 erase는 실제 객체를 제거한다. 하나를 지울 수 있는데 STL의 데이터 공간

novemberfirst.tistory.com

 

https://cplusplus.com/reference/algorithm/remove/

 

https://cplusplus.com/reference/algorithm/remove/

1234567891011121314 template ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator result = first; while (first!=last) { if (!(*first == val)) { if (result!=first) *result = move(*first); ++result; } ++first;

cplusplus.com