전체 글 (10)

08
08

1. isdigit

아스키 코드표에서 숫자('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')로 변환할 수 있는 값이 들어오면 True를 반환

string str = "1a2b";
bool tmp1 = isdigit(str[0]); //tmp1 = true
bool tmp2 = isdigit(str[1]); //tmp2 = false

2. toupper

인자로 입력받은 문자를 대문자로 바꾼다. (소문자는 tolower)

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

using namespace std;

string solution(string myString) {
    string answer = "";
    for(auto iter : myString)
        answer += toupper(iter);
     return answer;
}

주의할 점!!!

transform을 이용해도 똑같은 기능을 만들 수 있다.

하지만 using namespace std가 선언되어 있을 경우 (컴파일러에 따라 다른 결과를 내긴 했지만 적어도 프로그래머스에서는) transform 내부의 함수 포인터 toupper가 <locale>에 들어있는 인자를 두 개나 받는 std::toupper와 충돌을 일으키는 것 같다.

(위의 코드에서는 인자로 (iter)를 주는 것으로 자동 오버로딩 시키지만 아래에서는 함수 포인터?로? 사용해서 인자를 받지 않으므로 어떤 것으로 오버로딩할지 컴파일러가 결정하지 못한다?아마도?)

하지만 std::toupper는 우리가 사용하고 싶은 toupper (<ctype.h> 혹은 <cctype>에 들어있음)와 다르므로 transform의 인자로 사용할 수 없다.

따라서 ::toupper를 사용하여 전역 스코프에서 해당 함수를 찾아주어야 한다.

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

using namespace std;

string solution(string myString) {
    transform(myString.begin(), myString.end(),myString.begin(),::toupper);
    return myString;
}

아니면 다음과 같이 using namespace std를 사용하지 않는 방법도 있다.

#include <vector>
#include <algorithm>

std::string solution(std::string myString) {
    transform(myString.begin(), myString.end(),myString.begin(),toupper);
    return myString;
}

아니면 람다식을 사용하거나 함수 포인터 타입 변환으로 강제 오버로딩 시키는 방법도 있는 것 같다....

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

using namespace std;

string solution(string myString) {
    transform(myString.begin(), myString.end(),myString.begin(), [](unsigned char c){ return toupper(c);});
    return myString;
}
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(string myString) {
    transform(myString.begin(), myString.end(),myString.begin(),  (int (*)(int))toupper);
    return myString;
}

3. stoi(str)

문자열 str을 int로 변환해 반환

#include <string>
#include <vector>

using namespace std;

//n_str을 int형 정수로 변환해 반환
int solution(string n_str) {
    return stoi(n_str);
}

4. to_string(num)

숫자 num을 string 형식 문자열로 변환해 반환

#include <string>
#include <vector>

using namespace std;

//입력받은 int형 정수 n을 string으로 반환
string solution(int n) {
    return to_string(n);
}

5. stringstream

한 줄로 들어온 데이터에서 공백과 '\n'을 제외하고 문자열에서 맞는 자료형의 정보를 꺼냄

<sstream> 필요

#include <string>
#include <vector>
#include <sstream>

using namespace std;    

vector<string> solution(string my_string) {
    vector<string> answer;
    string str;
    stringstream ss;
    ss.str(my_string); //현재 stream의 값을 문자열로 바꿈
    while(ss >> str)
        answer.emplace_back(str);
    return answer;
}

6. regex_replace(string, regex("data"), "newdata")

문자열 string에서 data를 찾아 newdata로 치환

<regex> 필요

#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main(void)
{
    string str = "AAABBBCCC";
    str = regex_replace(str, regex("A"), "D"); //DDDBBBCCC
}

7. distance(first, last)

first에서 last 까지 거리가 얼마인지 반환

#include <string>
#include <vector>

using namespace std;

//arr 원소의 총 합 출력
int solution(vector<int> arr) {
    int dist = distance(arr.begin(),arr.end());
    return dist;
}

8. advance(iter, value)

iter를 value만큼 이동

#include <string>
#include <vector>

using namespace std;

//arr 원소의 총 합 출력
int solution(vector<int> arr) {
    auto iter = arr.begin();
    advance(iter,3); //iter를 3만큼 다음으로 움직인다
}

9. swap(value1, value2)

두 값을 서로 교환한다

#include <string>
#include <vector>

using namespace std;

//문자열 my_string의 [num1]과 [num2]를 바꾸어 출력한다
string solution(string my_string, int num1, int num2) {
    swap(my_string[num1],my_string[num2]);  
    return my_string;
}

10. 특수 문자 출력하기

cout 으로 출력할 때 몇몇 특수문자는 출력이 안된다

' (작은따옴표), " (큰따옴표)는 앞에 \를 붙인다(\' \")

\본인을 출력하고자 할 때에도 \\와 같이 사용한다

#include <iostream>

using namespace std;

//원하는 결과: !@#$%^&*(\'"<>?:;
int main(void) {
    //cout으로  특수 문자 출력하려면 앞에 \ 붙여야함
    cout << "!@#$%^&*(\\'\"<>?:;";
    return 0;
}

'C++ > 자료노트' 카테고리의 다른 글

<numeric>  (1) 2023.10.31
<vector>  (0) 2023.07.30
<algorithm>  (0) 2023.07.30
<string>  (0) 2023.07.30
COMMENT
 
07
30

1. .assign(first, last)

first 부터 last 전 까지의 원소들을 벡터에 대입한다. 이전에 있었던 원소들은 모두 삭제한다.

//{1,2,3,4,5} 1, 3 -> {2,3,4}
vector<int> solution(vector<int> numbers, int num1, int num2) {
   numbers.assign(begin(numbers)+num1, begin(numbers)+num2+1);
    return numbers;
}

2. .insert

  1.  .insert(iter, value): iter 위치에 value 삽입하고 위치 반환
  2.  .insert(iter, size, value): iter 위치에 value를 size 개수만큼 삽입
  3.  .insert(iter, first, last): iter 위치에 first 부터 last 전까지 값을 삽입
#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec(1,2);

  auto it = vec.insert(vec.begin(), 0); //벡터의 처음부분에 원소 0을 넣는다
  vec.insert(vec.begin(), 2, 3); //벡터의 처음부분에 3을 2개 넣는다
  
  vector<int> tempvec(10,11,12);
  vec.insert(vec.begin(), tempvec.begin(), tempvec.end()); //벡터의 처음부분에 tempvec의 처음부터 끝까지 넣는다
 
 return 0;
 }

'C++ > 자료노트' 카테고리의 다른 글

<numeric>  (1) 2023.10.31
기타 유용한 함수 등등  (0) 2023.08.08
<algorithm>  (0) 2023.07.30
<string>  (0) 2023.07.30
COMMENT
 
07
30

1. reverse(first, last)

first 부터 last 전 까지의 원소들의 순서를 역순으로 뒤집는다.

//{1,2,3,4} -> {4,3,2,1}
vector<int> solution(vector<int> num_list) {
    reverse(begin(num_list), end(num_list));
    return num_list;
}

2. count(first, last, val)

first 부터 last 전 까지의 원소들 중 val 과 일치하는 원소들의 개수를 반환한다.

//{1,1,2,3,4,1} -> 3 반환
int solution(vector<int> array, int n) {
    return count(begin(array), end(array), n);
}

3. sort(first,last)

first 부터 last 전 까지의 원소들을 오름차순으로 정렬한다.

//{1,3,4,2,5} -> {1,2,3,4,5}
int solution(vector<int> sides) {
    sort(sides.begin(),sides.end());
    return sides;
}

//rbegin(), rend()를 사용해 역순으로 정렬할 수 있다
//{1,3,4,2,5} -> {5,4,3,2,1}
int solution(vector<int> sides) {
    sort(sides.rbegin(),sides.rend());
    return sides;
}

//greater<int>(), less<int>()를 사용해 정렬 조건을 설정할 수 있다
int solution(vector<int> sides) {
	sort(sides.begin(),sides.end(),less<int>()); //오름차순
	sort(sides.begin(),sides.end(),greater<int>()); //내림차순
    return sides;
}

4. find(first,last,val)

first 부터 last 전 까지의 원소들 중 val과 일치하는 원소들 중 첫 번째 원소의 iter을 반환한다.

탐색에 실패했다면 last를 반환한다.

//{1,2,3,4,5}, 3 -> 3의 iter 리턴
int solution(vector<string> s1) {
    find(s2.begin(), s2.end(), 3);
    return answer;
}

5. remove(first,last,val)

first 부터 last 전까지의 원소들 중 val과 일치하는 원소를 발견하면 그 다음 요소부터 마지막 요소까지 모두 한 칸 앞으로 당겨오고, 이 이동의 끝점이자 남은 요소의 시작점의 iter를 반환한다.

//{BCBdbe}, B -> {Cdbebe} 두번째 b의 iter 반환
string solution(string my_string, string letter) {
    remove(my_string.begin(),my_string.end(),letter[0]);
    return my_string;
}

//{BCBdbe}, B -> {Cdbe}
//값을 완전히 제거하려면 .erase와 함께 사용하는 것이 좋다
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;
}

6. transform(first, last, d_first, unary_op)

first 부터 last 전까지의 원소들을 unary_op 함수에 인자로 전달한 후 그 결과값을 d_first 부터 연속되게 기록한다. (원소들을 특정 규칙에 맞춰 변환시킬 때 사용하면 좋은 듯)

//입력받은 string을 전부 대문자로 바꾸는 함수
//toupper에 ::가 붙은 이유는 기타 유용한 함수 게시글 참조 
string solution(string myString) {
    transform(myString.begin(), myString.end(),myString.begin(),  ::toupper);
    return myString;
}

7. rotate(first,middle,last)

first부터 last 전까지의 원소들을  middle을 첫 원소로 할 때까지 회전시킨다

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

//{1,2,3,4,5} -> {2,3,4,5,1}
vector<int> solution(vector<int> numbers) {
    rotate(numbers.begin(),numbers.begin()+1,numbers.end());
    return numbers;
}

8. min_element(first, last)

first부터 last 전까지의 원소들 중 최소값의 iter를 반환한다. (최대값은 max_element)

#include <vector>
#include <algorithm>
using namespace std;

//{1,2,3,4,5} -> 1 iter 반환
int solution(vector<int> numbers) {
    reuturn *min_element(numbers.begin(),numbers.end());
}

'C++ > 자료노트' 카테고리의 다른 글

<numeric>  (1) 2023.10.31
기타 유용한 함수 등등  (0) 2023.08.08
<vector>  (0) 2023.07.30
<string>  (0) 2023.07.30
COMMENT
 
1 2 3 4