반응형

 

1. 특정 문자열 하나를 다른 문자열로 치환하기

 

#include<iostream>
#include<string>
using namespace std;

int main() {
	string s = "hello, world";
	string prev = "world"; // 특정 문자열
	string next = "hello"; // 다른 문자열
	
	//find : 문자열을 못 찾으면 string::npos 값을 리턴, 찾으면 찾은 문자열의 시작 인덱스 리턴
	//replace(특정 문자열의 시작 인덱스, 특정 문자열의 길이, 다른 문자열)
	if (s.find(prev) != string::npos) {
		s.replace(s.find(prev), prev.length(), next);
	}
	cout << s; // hello, hello

	
	return 0;
}

 

2. 특정 문자열 모두를 다른 문자열로 치환하기

 

#include<iostream>
#include<string>
using namespace std;

int main() {
	string s = "hello, world, world, world";
	string prev = "world"; // 특정 문자열
	string next = "hello"; // 다른 문자열
	
	//find : 문자열을 못 찾으면 string::npos 값을 리턴, 찾으면 찾은 문자열의 시작 인덱스 리턴
	//replace(특정 문자열의 시작 인덱스, 특정 문자열의 길이, 다른 문자열)
	while (s.find(prev) != string::npos) {
		s.replace(s.find(prev), prev.length(), next);
	}

	cout << s; //hello, hello, hello, hello
	
	return 0;
}
반응형
반응형

set은 default로 오름차순으로 정렬되도록 구현이 되어있습니다. 

 

set에 type으로 class를 사용할 때 정렬 기준을 바꾸려면 set의 두 번째 인자로 operator()를 오버로딩한 구조체를 넘겨주면 됩니다.

 

예를 들어 다음과 같은 person class가 있다고 했을 때

1
2
3
4
5
6
7
8
9
class person{
public:
    int height;
    int weight;
    person(int height, int weight) {
        this->height = height;
        this->weight = weight;
    }
};
cs

set의 원소가 다음과 같은 조건을 만족하도록 정렬하고 싶으면

 

1. height가 작은 순서대로 정렬

2. height가 같으면 weight가 낮은 순서대로 정렬

 

다음과 같이 cmp 구조체를 만들면 됩니다. 

1
2
3
4
5
6
7
8
9
struct cmp {
   bool operator()(const person& a, const person& b) const{
        if (a.height == b.height) {
            return a.weight < b.weight;
        }
        return a.height < b.height;
    }
 
};
cs

 

 구현한 cmp 구조체를 set에 적용하려면 다음과 같이 set을 선언할 때 두 번째 인자로 cmp를 넘겨주면 됩니다.

1
 set<person, cmp> s;
cs

 

 
반응형
반응형

[c언어와의 호환성]

- C 언어의 문법 체계 계승

 

 

[입출력]

- 출력

std 이름 공간에 선언된 std::cout 사용

1
2
3
4
5
6
#include<iostream>
 
int main(void) {
    std::cout << "HelloWorld!\n";
    return 0;
}
cs

<< 연산자

-> 스트림 삽입 연산자(stream insertion operator)

-> c++ 기본 산술 시프트 연산자 <<가 <iostream> 헤더 파일에 삽입 연산자로 재정의됨

-> 오른쪽 피연산자를 왼쪽 스트림 객체에 삽입

-> cout 객체에 연결된 화면에 출력

-> 연속된 << 연산자로 여러 값 출력 가능 : std::cout << a << b << c;

 

- 입력

std 이름 공간에 선언된 std::cin 사용

1
2
3
4
5
6
7
#include<iostream>
 
int main(void) {
    int key;
    std::cin >> key;
    return 0;
}
cs

 

 

>> 연산자

-> 스트림 추출 연산자(stream extraction operator)

-> c++ 산술 시프트 연산자 >>가 <iostream> 헤더 파일에 스트림 추출 연산자로 재정의됨

-> 입력 스트림에서 값을 읽어 변수에 저장

-> 연속된 >> 연산자로 여러 값 입력 가능 : std::cin>>a>>b>>c;

 

 

[namespace]

- 변수명 등 이름 충돌이 발생하는 경우 해결에 많은 시간이 필요하다

- 여러 명이 서로 나누어 프로젝트를 개발하는 경우

- 오픈 소스 혹은 다른 사람이 작성한 코드를 가져와서 컴파일 하거나 링크하는 경우

 

namespace 키워드

개발자가 자신만의 이름 공간을 생성해서 다른 이름공간과 구분하여 충돌 해결

1
2
3
4
5
6
7
8
9
10
#include<iostream>
 
namespace my {
    int myVal = 10;
}
 
int main(void) {
    std::cout << my::myVal;
    return 0;
}
cs

 

using 키워드를 사용하면 ~ :: 를 생략할 수 있음 (using namespace std;  -> std:: 생략하고 바로 cout 사용 가능)

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;
namespace my {
    int myVal = 10;
}
 
 
int main(void) {
 
    using namespace my;
    cout <<myVal;
    return 0;
cs

 

 

[객체 지향 개념 도입]

- 캡슐화, 상속, 다형성
- 재사용을 통해 생산성 향상, 큰 규모의 sw의 작성, 유지보수 용이

 

[함수 오버로딩(function overlading)]

- 매개 변수의 개수나 타입이 다른 동일한 이름의 함수들 선언

 

[디폴트 매개 변수(default parameter)]

- 매개 변수에 디폴트 값이 전달되도록 함수 선언

 

[참조와 참조 변수(reference)]

- 하나의 변수에 별명을 사용하는 참조 변수 도입

 

[call-by-address, call-by-reference, call-by-value]

 

[new/delete 연산자]

- 동적 메모리 할당/해체

 

[연산자 재정의]

- 기존 C++ 연산자에 새로운 연산 정의

 

[제네릭 함수와 클래스]

- 데이터 타입에 의존하지 않고 일반화시킨 함수나 클래스 작성 가능

 

[캡슐화]

- 데이터를 캡슐로 싸서 외부의 접근으로부터 보호

- class에서 접근 지정자로 표현한다

 

[클래스와 객체]

- 클래스: 객체를 만드는 템플릿

- 객체(object) : 클래스를 통해서 생겨난 실체

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;
 
class Circle {
private// 캡슐화
    int radius;
public:
    Circle(int r) {
        radius = r;
    }
    double getArea() {
        return 3.14 * radius * radius;
    }
};
 
int main(void) {
    Circle obj(3); //객체 생성
    cout << obj.getArea();
 
    return 0;
}
cs

 

 

[객체 지향 상속(Inheritance)]

- 자식이 부모의 유전자를 물려 받는 것

[C++ 상속]

-기존 클래스를 재사용 또는 확장하여 새로운 클래스를 작성하는 것

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using namespace std;
 
class animal {
public:
    void breathe() {
        cout << "숨쉬기" << endl;
    }
};
 
class pigeon : public animal { //animal 상속
public:
    void fly() {
        cout << "날다" << endl;
    }
};
class monkey : public animal { //animal 상속
public:
    void walk(){
        cout << "걷는다" << endl;
    }
};
 
int main(void) {
    pigeon p;
    p.fly();
    monkey m;
    m.walk();
 
    return 0;
}
cs

[다형성(Polymorphism)]

- 서로 다른 객체가 동일한 메시지에 대해 다른 방법으로 응답할 수 있는 기능

- 연산자 중복, 함수 중복, 함수 오버라이딩(overriding)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
using namespace std;
 
class animal {
public:
    void move() {
        cout << "움직인다" << endl;
    }
};
 
class pigeon : public animal { //animal 상속
public:
    void move() {
        cout << "날아서 움직인다" << endl;
    }
};
 
class monkey : public animal { //animal 상속
public:
    void move() {
        cout << "걸어서 움직인다" << endl;
    }
};
 
int main(void) {
    pigeon p;
    p.move();
    monkey m;
    m.move();
 
    return 0;
}
cs

 

[소프트웨어 생산성 향상]

- 소프트웨어의 생명 주기 단축 문제 해결 필요

- 기 작성된 코드의 재사용 필요

- C++ 클래스 상속 및 객체 재사용으로 해결

 

[실세계에 대한 쉬운 모델링]

- 실세계는 객체로 구성된 세계이다.

- 객체를 중심으로 하는 객체 지향 언어를 사용하면 쉽게 실세계를 모델링할 수 있다.

 

[절자치향 vs 객체지향 차이]

- 절차 지향

실행하고자 하는 절차대로 일련의 명령어 나열

흐름도를 설계하고 흐름도에 따라 프로그램 작성

- 객체 지향

객체들을 정의하고, 객체들의 상호 관계, 상호 작용으로 구현

 

[제네릭 함수(generic function)]

- 동일한 프로그램 코드에 다양한 데이터 타입을 적용할 수 있게 일반화시킨 함수

1
2
3
4
5
6
7
8
9
10
void swap(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}
void swap(double& a, double& b) {
    double temp = a;
    a = b;
    b = temp;
}
cs

위 코드는 함수 오버로딩(재정의)를 통해 같은 코드를 타입만 달리하여 구현하였는데 이는 너무 비효율적이다. 이를 해결하기 위해 다음과 같이 제네릭 함수를 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;
 
template<class T> //템플릿 선언 및 제네릭 타임 T 선언
void newSwap(T& a, T& b) {
    int temp = a;
    a = b;
    b = temp;
}
int main(void) {
    int a = 10;
    int b = 20;
    newSwap(a, b); //제네릭 타입 T에 int를 구체화 시켜 함수를 생성 후 호출
    cout << a << ", " << b << endl;
 
    return 0;
}
cs

 

[제네릭 클래스(generic class)]

- 동일한 프로그램 코드에 다양한 데이터 타입을 적용할 수 있게 일반화시킨 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class calulator {
public:
    int mul(int a, int b) {
        return a * b;
    }
    int div(int a, int b) {
        return a / b;
    }
    int sub(int a, int b) {
        return a - b;
    }
    int add(int a, int b) {
        return a + b;
    }
};
 
cs

위 코드는 두 수를 입력받아 계산해주는 작업을 해주는 클래스인데 지금은 정수형 계산만 가능하다. 만약에 다른 타입을 입력 받아 계산하고 싶다면 모든 타입에 대해 함수 오버로딩을 해야 한다. 이는 너무 비효율적이므로 아래와 같이 제네릭 클래스를 사용하면 효율적으로 코드를 생성할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
using namespace std;
 
template<typename T>//제네릭 클래스 선언
class calulator {
public:
    T mul(T a, T b) {
        return a * b;
    }
    T div(T a, T b) {
        return a / b;
    }
    T sub(T a, T b) {
        return a - b;
    }
    T add(T a, T b) {
        return a + b;
    }
};
 
int main(void) {
    calulator<double> c; //제네릭 클래스를 double로 구체화해서 객체 생성
    cout << c.mul(2.33.4);
    return 0;
}
cs

 

[C++ 프로그램 개발 과정]

 

1. hello.cpp 소스 파일 작성

2. 컴파일 -> 목적 파일 (hello.obj) 생성
3. 링킹 -> c++ 라이브러리, 여러 목적 파일을 묶어서 실행 파일로 만든다

4. 로더 -> 실행 파일을 메모리에 적재하고 실행시킨다.

 

c++ STL 라이브러리

- 제네릭 프로그래밍을 지원하기 위한 템플릿 라이브러리

- vector, queue, stack... 등

 

 

 

반응형
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <windows.h>
using namespace std;
 
 
/*커서 숨기기(0) or 보이기(1) */
void CursorView(char show) {
    HANDLE hConsole;
    CONSOLE_CURSOR_INFO ConsoleCursor;
 
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
 
    ConsoleCursor.bVisible = show;
    ConsoleCursor.dwSize = 1;
 
    SetConsoleCursorInfo(hConsole, &ConsoleCursor);
}
 
 
int main(void) {
    //CursorView(true); // 커서 보이기
    CursorView(false); // 커서 숨기기
    return 0;
}
cs

include <windows.h>

반응형
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <windows.h>
using namespace std;
 
/*콘솔 커서 위치 이동*/
void gotoxy(int x, int y) {
    COORD pos = { x,y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
 
int main(void) {
    gotoxy(63); // x좌표가 y좌표보다 크기가 2배 정도 작다.
    cout << ". -> (6,3)";
    return 0;
}
cs

include <windows.h>

void gotoxy(int x, int y) {

    COORD pos = { x,y };

    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);

}

 

→ x축

↓ y 축

x좌표가 y좌표보다 크기가 2배 정도 작다.

호출 ex) gotoxy(6, 3);

반응형
반응형

system("mode con cols=가로 길이 lines=세로 길이 | title 제목명");

세로 길이가 가로 길이 보다 길다

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
 
int main(void) {
   system("mode con cols=30 lines=30 | title 제목명"); // 콘솔창 크기 및 제목 설정
   //cols = 가로, lines = 세로 (가로가 세로보다 짧음)
   getchar();
   return 0;
}
cs

 

반응형

'C++' 카테고리의 다른 글

[C/C++] 콘솔 커서 숨기기  (0) 2020.03.25
[C/C++] 콘솔 커서 위치 이동하기  (0) 2020.03.25
[c++] int을 string으로 변환하기  (0) 2020.03.25
[c++] string을 int로 변환하기  (0) 2020.03.25
[C/C++] 음수 모듈러 연산  (1) 2020.02.28
반응형

[c++]

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
 
int main(void) {
    int num = 1234;
    stringstream ss;
    ss << num;
    string str = ss.str();
    cout << str;
    return 0;
}
cs

[C++ 11 ~]

string to_string (int val);

string to_string (long val);

string to_string (long long val);

string to_string (unsigned val);

string to_string (unsigned long val);

string to_string (unsigned long long val);

string to_string (float val);

string to_string (double val);

string to_string (long double val);

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
using namespace std;
 
int main(void) {
    int num = 1234;
    string str = to_string(num);
    cout << str;
    return 0;
}
cs

 

 

반응형
반응형

[c++]

int atoi (const char * str) - ascii to integer

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;
 
int main(void) {
    string str = "1234";
    //atoi 파라미터는 char* 이므로 stirng을 char* 변환해서 인자로 넘겨야함
    int num = atoi(str.c_str()); // ascii to integer
    cout << num;
    return 0;
}
cs

 

[c++ 11 ~]

int stoi (const string& str, size_t* idx = 0, int base = 10);

 

첫 번째 인자: 정수로 표현할 문자열

두 번째 인자: 정수 다음에 나온 문자의 포인터를 가리킨다.

ex("1234abcd"이면 'a'를 위치를 가리킨다 -> idx = 4)

세 번째 인자: 진수

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
using namespace std;
 
int main(void) {
    string str = "1234";
    int num = stoi(str); // string to integer
    cout << num;
    return 0;
}
cs

 

 

반응형

+ Recent posts