[내일배움캠프 Day13] C++ 2주차 과제 진행

2025. 1. 3. 22:20·내일배움캠프/TIL

[3번 과제] 템플릿 및 STL

SimpleVector.h

#pragma once
#include <iostream>
#include <algorithm>

template <typename T>
class SimpleVector {
private:
	T* data;
	int currentSize;
	int currentCapacity;

public:
	// 기본 생성자
	SimpleVector() : currentSize(0), currentCapacity(10) {
		data = new T[currentCapacity];
	}

	// 용량 지정 생성자
	SimpleVector(int capacity) : currentSize(0), currentCapacity(capacity) {
		data = new T[currentCapacity];
	}

	// 복사 생성자
	SimpleVector(const SimpleVector& other) : currentSize(other.currentSize), currentCapacity(other.currentCapacity) {
		data = new T[currentCapacity];
		for (int i = 0; i < currentSize; ++i) {
			data[i] = other.data[i];
		}
	}

	// 소멸자
	~SimpleVector() {
		delete[] data;
	}

	// 인자로 받은 원소를 맨 뒤에 추가
	void push_back(const T& value) {
		if (currentSize >= currentCapacity) {
			return;
		}
		data[currentSize++] = value;
	}

	// 마지막 원소를 제거
	void pop_back() {
		if (currentSize > 0) {
			--currentSize;
		}
	}

	// 현재 원소의 개수를 반환
	int size() const {
		return currentSize;
	}

	// 현재 배열의 크기를 반환
	int capacity() const {
		return currentCapacity;
	}

	// 배열의 크기 재할당
	void resize(int newCapacity) {
		if (newCapacity <= currentCapacity) return;

		T* newData = new T[newCapacity];
		for (int i = 0; i < currentSize; ++i) {
			newData[i] = data[i]; 
		}
		delete[] data;

		data = newData; 
		currentCapacity = newCapacity;
	}

	// 내부 데이터를 정렬하는 함수
	void sortData() {
		std::sort(data, data + currentSize);
	}

	void print() const {
		for (int i = 0; i < currentSize; ++i) {
			std::cout << data[i] << " ";
		}
		std::cout << std::endl;
	}
};

 

main.cpp

#include "SimpleVector.h"
#include <iostream>

int main() {
	SimpleVector<int> vec;

	vec.push_back(5);
	vec.push_back(3);
	vec.push_back(7);

	vec.print();

	vec.sortData();
	std::cout << "정렬 후 : ";
	vec.print();

	vec.pop_back();
	std::cout << "마지막 원소 제거 후 : ";
	vec.print();

	return 0;
}

 

 

[4번 과제] C++ Summary

 

Book.h

#pragma once
#include <string>

using namespace std;

class Book {
private:
    string title;
    string author;

public:
    Book(const string& title, const string& author);
    string getTitle() const;
    string getAuthor() const;
};

Book.cpp

#include "Book.h"

Book::Book(const string& title, const string& author)
    : title(title), author(author) {}

string Book::getTitle() const
{
    return title;
}

string Book::getAuthor() const
{
    return author;
}

BookManager.h

#pragma once
#include <vector>
#include "Book.h"

class BookManager {
private:
	vector<Book> books;

public:
    void addBook(const string& title, const string& author);
    void displayAllBooks() const;
    Book* findBookByTitle(const string& title);
    Book* findBookByAuthor(const string& author);
};

BookManager.cpp

#include "BookManager.h"
#include <iostream>

using namespace std;

// 책 추가 
void BookManager::addBook(const string& title, const string& author)
{
	books.push_back(Book(title, author)); 
	cout << "책이 추가되었습니다: " << title << " by " << author << endl;
}

// 모든 책 출력
void BookManager::displayAllBooks() const
{
    if (books.empty()) {
        cout << "현재 등록된 책이 없습니다." << endl;
        return;
    }

    cout << "현재 도서 목록:" << endl;
    for (auto& book : books) { 
        cout << "- " << book.getTitle() << " by " << book.getAuthor() << endl;
    }
}

// 책 제목으로 검색
Book* BookManager::findBookByTitle(const string& title)
{
    for (auto& book : books) {
        if (book.getTitle() == title)
            return &book;
    }
    return nullptr;
}

// 책 작가로 검색
Book* BookManager::findBookByAuthor(const string& author)
{
    for (auto& book : books) {
        if (book.getAuthor() == author)
            return &book;
    }
    return nullptr;
}

BorrowManager.h

#pragma once
#include <unordered_map>
#include "Book.h"

using namespace std;

class BorrowManager{
private:
	unordered_map<string, int> stock;

public:
    void initializeStock(Book* book, int quantity = 3);
    void borrowBook(const string& title);
    void returnBook(const string& title);
    void displayStock() const;
};

BorrowManager.cpp

#include "BorrowManager.h"
#include <iostream>

using namespace std;

void BorrowManager::initializeStock(Book* book, int quantity)
{
	stock[book->getTitle()] = quantity;
}

void BorrowManager::borrowBook(const string& title)
{
	auto it = stock.find(title);
	if (it != stock.end() && it->second > 0) {
		it->second--;
		cout << title << "대여 완료. 남은 수량 : " << it->second << endl;
	}
	else {
		cout << "대여 불가" << endl;
	}
}

void BorrowManager::returnBook(const string& title)
{
	auto it = stock.find(title);
	if (it != stock.end() && it->second < 3) {
		it->second++;
		cout << title << " 반납 완료. 현재 수량 : " << it->second << endl;
	}
	else {
		cout << "반납 불가" << endl;
	}
}

void BorrowManager::displayStock() const
{
	cout << "현재 도서 재고 현황:" << endl;
	for (auto& book : stock) {
		cout << "- " << book.first << " : " << book.second << "권" << endl;
	}
}

main.cpp

#include <iostream>
#include "BookManager.h"
#include "BorrowManager.h"

int main() {
    BookManager bookManager;
    BorrowManager borrowManager;
    string title, author;

    cout << "\n도서관 관리 프로그램" << endl;
    cout << "1. 책 추가" << endl;
    cout << "2. 모든 책 출력" << endl;
    cout << "3. 제목으로 책 검색" << endl;
    cout << "4. 작가로 책 검색" << endl;
    cout << "5. 책 대여" << endl;
    cout << "6. 책 반납" << endl;
    cout << "7. 재고 현황 확인" << endl;
    cout << "8. 종료" << endl;

    while (true) {
        cout << "선택: ";

        int choice;
        cin >> choice;
        cin.ignore();

        switch (choice) {
        case 1: {
            cout << "책 제목: ";
            getline(cin, title);
            cout << "책 저자: ";
            getline(cin, author);
            bookManager.addBook(title, author);
            auto book = bookManager.findBookByTitle(title);
            if (book) {
                borrowManager.initializeStock(book);
            }
            break;
        }
        case 2:
            bookManager.displayAllBooks();
            break;
        case 3: {
            cout << "검색할 책 제목: ";
            getline(cin, title);
            auto book = bookManager.findBookByTitle(title);
            if (book) {
                cout << "검색 결과: " << book->getTitle() << " by " << book->getAuthor() << endl;
            }
            else {
                cout << "책을 찾을 수 없습니다." << endl;
            }
            break;
        }
        case 4: {
            cout << "검색할 작가 이름: ";
            getline(cin, author);
            auto book = bookManager.findBookByAuthor(author);
            if (book) {
                cout << "검색 결과: " << book->getTitle() << " by " << book->getAuthor() << endl;
            }
            else {
                cout << "책을 찾을 수 없습니다." << endl;
            }
            break;
        }
        case 5:
            cout << "대여할 책 제목: ";
            getline(cin, title);
            borrowManager.borrowBook(title);
            break;
        case 6:
            cout << "반납할 책 제목: ";
            getline(cin, title);
            borrowManager.returnBook(title);
            break;
        case 7:
            borrowManager.displayStock();
            break;
        case 8:
            cout << "프로그램을 종료합니다." << endl;
            return 0;
        default:
            cout << "잘못된 입력입니다. 다시 시도하세요." << endl;
        }
    }

    return 0;
}

 

'내일배움캠프 > TIL' 카테고리의 다른 글

[내일배움캠프 Day15] 디자인 패턴 - 구조 패턴  (2) 2025.01.09
[내일배움캠프 Day14] 디자인 패턴 - 생성 패턴  (1) 2025.01.06
[내일배움캠프 Day12] 반복자와 포인터  (2) 2025.01.02
[내일배움캠프 Day11] 템플릿  (3) 2024.12.31
[내일배움캠프 Day10] 메모리 관리  (0) 2024.12.31
'내일배움캠프/TIL' 카테고리의 다른 글
  • [내일배움캠프 Day15] 디자인 패턴 - 구조 패턴
  • [내일배움캠프 Day14] 디자인 패턴 - 생성 패턴
  • [내일배움캠프 Day12] 반복자와 포인터
  • [내일배움캠프 Day11] 템플릿
개발자 밍
개발자 밍
dev0404 님의 블로그 입니다.
  • 개발자 밍
    Developer
    개발자 밍
  • 전체
    오늘
    어제
    • 분류 전체보기 (88)
      • 강의 (8)
        • UE Climbing System (3)
        • UE Dungeon (1)
        • HCI (4)
      • 책 (18)
        • 객체지향의 사실과 오해 (5)
        • Effective C++ (3)
        • 이득우의 게임 수학 (4)
        • 이것이 취업을 위한 컴퓨터 과학이다 (4)
        • 리뷰 (2)
      • C++ (2)
      • 알고리즘 (2)
      • 자료구조 (1)
      • Unreal (4)
      • 내일배움캠프 (52)
        • TIL (52)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자료구조
    c++
    알고리즘
    게임수학
    언리얼
    컴퓨터구조
    내일배움캠프
    객체지향
    그래픽스
    Effective
    컴퓨터 구조
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
개발자 밍
[내일배움캠프 Day13] C++ 2주차 과제 진행
상단으로

티스토리툴바