TIL
[241223 TIL] C++ 실습_vector STL
yoosorang
2024. 12. 23. 20:51
⁉️ 상기시키기
▪ 인텔리센스 : 코드 문법 자동 완성
▪ getline(cin, name); //string에 문자를 입력하는 방법
▪ 현업에서는 a, b, c 이런 거 말고 의미 있는 이름의 변수를 사용해야 함
▪ char letters[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; //문자열의 마지막에 끝을 알리는 개행 문자 넣어줘야함
▪ int zeroArray[5] = {0}; // 첫 번째 값만 0으로 초기화하면 나머지도 0으로 초기화
▪ 함수에 일반 변수를 전달하면 원본 변수 변경X(복사 전달이라)
▪ 함수 입장에서는 배열의 크기를 모르니까 인자로 배열을 전달할 때 크기까지 같이 전달해줌
▪ 과도한 들여쓰기는 코드를 복잡하게 보이게 함 → 한 눈에 봐도 알 수 있도록 코드를 짜는 게 중요
❗New Knowlodge
▪ C++ 랜덤 함수
▪ virtual : 실제 호출 시 파생 클래스를 확인 → 가상함수
▪ 순수가상함수는 재정의하는 것이 필수 가상함수 정의 = 0을 붙이면 순수 가상함수
▪ 추상 클래스 : 순수가상함수를 포함한 클래스 → 변수로 사용할 수 없고(인스턴스 생성 불가능) 포인터로만 사용 가능
▪ 정적 배열 사용하여 클래스 변수 선언 시 기본 생성자만 호출됨 -> 동적 배열 사용 필요
▪ 동적 배열 사용시 new 연산자를 사용해 원하는 시점에 객체 생성(직접 메모리 관리 필요 - delete)
랜덤 숫자 뽑기
#include <cstdlib>
#include <ctime>
int main(){
srand(time(0));
int secretNumber = rand() % 100 + 1;
}
1️⃣ C++ 실습
1. 다이아몬드 모양 별 찍기
//풀이 1 반복문
#include <iostream>
using namespace std;
int main()
{
int userNum =1;
while (userNum > 0)
{
cout << "정수인 숫자를 입력해주세요.";
cin >> userNum;
cout << endl;
for (int i = 0; i < userNum; i++) //상단
{
for (int j = 1; j < userNum-i ; j++)
{
cout << " ";
}
for (int j = 1; j < 2*i+2 ; j++)
{
cout << "*";
}
for (int j = 1; j < userNum - i; j++)
{
cout << " ";
}
cout << endl;
}
for (int i = 0; i < userNum - 1; i++) //하단
{
for (int j = 1; j < i+2; j++)
{
cout << " ";
}
for (int j = 1; j < 2 * (userNum-2 - i) + 2 ; j++)
{
cout << "*";
}
for (int j = 1; j < i + 2; j++)
{
cout << " ";
}
cout << endl;
}
}
}
//풀이2 조건문
#include <iostream>
using namespace std;
int main()
{
int userNum =1;
cout << "정수인 숫자를 입력해주세요.";
cin >> userNum;
for (int i = 0; i < userNum * 2 - 1; i++)
{
for (int j = 0; j < userNum * 2 - 1; j++)
{
if (i <= userNum - 1)
{
if (userNum - 1 - i <= j && j <= userNum - 1 + i)
cout << "*";
else
cout << " ";
}
else
{
if (userNum - 1 - (userNum * 2 - i - 2) <= j && j <= userNum - 1 + (userNum * 2 - i - 2))
cout << "*";
else
cout << " ";
}
}
cout << endl;
}
}
💭자아성찰
▪ 공백이어서 한 줄 중 뒤에 부분에 있는 공백은 코드 따로 안 적어도 됨(공백에 대한 유연성을 생각했어야 했음)
▪ 조건문이 좀 지저분한 것 같음 -> 변수로 따로 지정해주던가 할 걸
▪ 문제 : (userNum - 1 - i <= j <= userNum - 1 + i)를 조건으로 넘겨서 계속 *만 찍혔음
▪ 해결과정: cout << "*"<< userNum - 1 - i << j << userNum - 1 + i; 디버깅 추가하여 코드 흐름 확인
▪ 해결: 복합 조건 사용
2. 배터리 관리 클래스 만들기
//Battery.h
#ifndef BATTERY_H_
#define BATTERY_H_
class Battery {
public:
Battery(int initialCharge = 100) {
charge = initialCharge;
}
int getCharge() { return charge; }
void useBattery();
void chargeBattery();
private:
int charge = 0;
};
#endif
//Battery.cpp
#include "Battery.h"
#include <iostream>
using namespace std;
int main() {
Battery b; //생성자도 public으로 선언해야 함
cout << "Initial charge: " << b.getCharge() << "%" << endl;
b.useBattery();
b.useBattery();
b.chargeBattery();
b.useBattery();
return 0;
}
void Battery::useBattery() {
charge -= 5;
cout << "Batery used. Current charge: " << getCharge() << "%" << endl;
}
void Battery::chargeBattery() {
charge += 7;
cout << "Batery charged. Current charge: " << getCharge() << "%" << endl;
}
💭자아성찰
▪ 범위 외의 예외처리가 빠짐
▪ 하나의 파일로 만드는 줄 모르고 따로 작성함
3. 두 분수의 곱셉을 할 수 있는 클래스 만들기
#include <iostream>
using namespace std;
class Fraction {
public:
Fraction() {
numerator = 0;
denominator = 1;
}
Fraction(int numerator = 0, int denominator = 1) {
this->numerator = numerator;
this->denominator = denominator;
}
void simplify();
Fraction multiply(Fraction num1, Fraction num2);
void display();
int gcd(int a, int b);
private:
int numerator;
int denominator;
};
void Fraction::simplify(){
int maxCommonDivisor = gcd(numerator, denominator);
numerator /= maxCommonDivisor;
denominator /= maxCommonDivisor;
}
Fraction Fraction::multiply(Fraction num1, Fraction num2) {
int numMul = num1.numerator* num2.numerator;
int denomMul = num1.denominator * num2.denominator;
return Fraction(numMul, denomMul);
}
void Fraction::display() {
cout << "곱한 결과: " << numerator << "/" << denominator << endl;
}
int Fraction::gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() { //main은 맨 마지막에
Fraction f1(4, 8);
Fraction f2(6, 10);
Fraction f3 = f1.multiply(f1, f2);
f3.simplify();
f3.display();
return 1;
}
💭자아성찰
▪ gcd는 fraction클래스 내부에서만 사용되니까 private에 작성
▪ 포함시킬 수 있는 함수는 포함시키기 → simplify
▪ 또또 예외처리!!
4. 다형성을 활용한 게임 스킬 사용 프로그램
#include <iostream>
using namespace std;
class Adventure {
public:
virtual void useSkill() = 0;
};
class Warrior : public Adventure {
void useSkill() {
cout << "Warrior uses Slash!" << endl;
}
};
class Mage : public Adventure {
void useSkill() {
cout << "Mage casts Fireball!" << endl;
}
};
class Archer : public Adventure {
void useSkill() {
cout << "Archer shoots an Arrow!" << endl;
}
};
int main() {
Adventure* player[3];
player[0] = new Warrior();
player[1] = new Mage();
player[2] = new Archer();
for (int i = 0; i < 3; i++)
{
player[i]->useSkill();
delete player[i];
}
return 1;
}
💭자아성찰
▪ 답안은 vector 사용
2️⃣ 추가 공부
🔹Vector 정리
Vector
정적 배열(array)에 대응하는 동적 배열(dynamic array)에 해당(python 리스트 같은 거)❓왜 vector일까?STL → 데이터 구조에 대해 직관적이고 수학적 개념에서 영감1. 수학적 벡터의 배열성메모리 상에서
yoosorang.tistory.com