TIL

[241226 TIL] C++ 공부_입력 예외 처리

yoosorang 2024. 12. 26. 18:34

0️⃣ New Knowledge

▪ rand() 함수

#include<cstdlib>
#include<ctime>
rand() % 3; //0~2 중 랜덤한 수


▪ 반올림 : round(number)
 
▪ accumulate(first, last, init, op): 컨테이너의 요소를 효율적으로 누적하거나, 원하는 방식으로 처리하는 데 사용  
기본 연산은 더하기(+), 필요 시 사용자 정의 연산 가능 ->  op

vector<int> numbers = {1,2,3,4,5};
int product = accumulate(numbers.begin(), numbers.end(), 1, [](inta,intb) {return a * b});// 곱셈 연산
vector<string> words = {"Hello"," ","World","!"};
string result =accumulate(words.begin(), words.end(),string(""));
cout <<"Result: "<< result << endl;// 출력: Hello World!


▪ STL(Standard Template Library)은 C++자체 제공 표준 라이브러리로 컨테이너와 알고리즘 구현

▪ 컨테이너 : 데이터를 담는 자료구조(템플릿으로 구현, 메모리 자동 관리)
-벡터 : 크기가 자동 관리 되는 배열
-맵 : 인덱스 대신 키(Key) 사용(키-값)

▪ 알고리즘 : sort, find

▪ 반복자 : 컨테이너 각각을 같은 문법으로 사용 가능하게 함(순방향 반복자, 역방향 반복자)

 

1️⃣ C++ 개념 강의

🔹 반복자를 화용하여 각 컨테이너를 순회하기

#include <iostream>
#include <vector>
#include <map>

using namespace std;

int main() {
	vector<int> vec = { 10, 20, 30, 40, 50 };
	map<string, int> mp = {
		{"Alice", 90},
		{"Bob", 85},
		{"Charlie", 95}
	};

	for (auto it = vec.begin(); it != vec.end(); it++) {
		cout << *it << " ";
	}

	cout << endl;

	for (auto it = vec.rbegin(); it != vec.rend(); it++) {
		cout << *it << " ";
	}

	cout << endl;

	for (auto it = mp.begin(); it != mp.end(); it++) {
		cout << it-> first << " : " << it -> second << endl;
	}

	for (auto it = mp.rbegin(); it != mp.rend(); it++) {
		cout << it->first << " : " << it->second << endl;
	}

}
코드스니펫에서 반복문을 쓸 때 전위증가를 사용하는 이유

전위 증가
: 값을 증가시키고 증가된 값을 반환

후위 증가
: 값을 증가시키지만 이전 값을 복사하여 반환한 후에증가

반복문처럼 자주 호출되는 경우 누적 성능 차이를 줄이는 데 유리
(반복자를 사용할 때는 ++it를 선호하는 것이 일반적)

 

🔹과제

▪️ OOP Summary

class Zoo {
private:
	Animal* animals[10];
	int animalCount = 0;

public:
	Zoo() {
		cout << "Welcome to the Zoo!" << endl;
	}

	void addAnimal(Animal* animal) {
		if (animalCount >= 10) { 
        	//추가에 대한 제한 안해주면 에러
			cout << "Sorry but Zoo is full!";
			return;
		}
		cout << "New friend joins!" << endl;
		animals[animalCount] = animal;
		animalCount++;

	}

	void performAction() {
		cout << "\nAll animals make sound!" << endl;
		for (int i = 0; i<animalCount; i++) 
        	//for(auto animal : animals) 사용했다가 잘못 접근해서 에러 뜸
		{
			animals[i]->makeSound();
		}
	}

	~Zoo() {
		cout << "See you Again!" << endl;
		for (int i = 0; i < animalCount; i++)
		{
			delete animals[i]; 
		}
		//delete[] animals
		//배열 메모리 해제 시도했더니 중단점 명령이 실행되었다는 에러 발생
	}
};
💭자아성찰
반복에 대한 예외처리를 안 해줘서 에러와 많이 부딪힘.

 

▪️ 간단한 프로그래밍 구현 미니 과제_문자열 예외 처리 추가

 

2️⃣ 추가 공부

▪️ 입력 예외 처리

 

입력 예외 처리

#include using namespace std;int main(){ int num; cout > num; if(cin.fail()){ //입력 실패 여부 cout ::max(), '/n'); //남은 입력 버퍼 제거 } else{ cout 📌 입력 버퍼1. 사용자의 입력 > 입력 버퍼에 저장2. 프로그램에서 데

yoosorang.tistory.com