[3번 과제] 템플릿 및 STL

정채은·2025년 6월 17일

C++ 프로그래밍

목록 보기
10/16

✅ 필수 기능 가이드

  • 클래스의 이름은 SimpleVector라고 합니다.
  • 타입에 의존하지 않고 데이터를 받을수 있는 배열을 멤버변수로 갖습니다.
  • 생성자는 아래와 같이 구현 합니다.
    • 기본 생성자는 크기가 10인 배열을 만듭니다.
    • 숫자를 하나 받는 생성자는 해당 숫자에 해당되는 크기의 배열을 만듭니다.
  • 아래와 같은 멤버함수를 구현 합니다.
    • push_back 인자로 받은 원소를 맨 뒤에 추가 합니다. 반환값은 없습니다. 배열의 크기가 꽉 찼는데 원소가 더 들어올경우 아무 동작도 하지 않습니다.
    • pop_back은 벡터의 마지막 원소를 제거 합니다. 만약 제거할 원소가 없다면 아무 동작도 하지 않으며, 인자 및 반환값은 없습니다.
    • size는 인자가 없고 현재 원소의 개수를 반환합니다.
    • capacity 현재 내부 배열의 크기를 반환합니다.

구현을 한 뒤에 클래스의 구조는 아래와 같습니다.

🔥 도전 기능 가이드

필수 기능을 모두 완료한 후, 아래 기능을 추가 합니다.

  • 복사 생성자를 구현 합니다.
  • 아래 멤버함수를 추가로 변경/구현 합니다.
    • push_back에서 배열의 크기가 꽉 찼는데 원소가 더 들어올경우, 기존 배열보다 크기를 5만큼 더 늘리고 새로운 원소까지 추가됩니다.
      (기존에 있던 값도 유지되야 합니다.)
    • resize는 정수 하나를 인자로 받습니다. 해당 정수가 현재 배열의 크기보다 작으면 아무 동작도 하지 않습니다. 만약 현재 배열보다 크기가 크면 해당 값만큼 크기를 재할당 합니다.
      (기존 원소는 그대로 있어야 합니다.)
    • sortData는 내부 데이터를 정렬하는 함수 입니다. 직접 정렬하지 않고 STL의 sort함수를 활용해서 정렬 합니다.

구현을 한 뒤에 클래스의 구조는 아래와 같습니다.

내가 짠 코드

SimpleVector.cpp

#include <iostream>
#include <algorithm>

using namespace std;

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

public:
	SimpleVector()
		: data(new T[10]), currentCapacity(10), currentSize(0) {
	}

	SimpleVector(int x)
		: data(new T[x]), currentCapacity(x), currentSize(0) {
	}

	SimpleVector(const SimpleVector& other)
		: data(new T[other.currentCapacity]), currentSize(other.currentSize), currentCapacity(other.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)
		{
			if (0 < currentCapacity)
			{
				int newCapacity = currentCapacity + 5;
				T* tmpData = new T[newCapacity];
				for (int i = 0; i < currentSize; ++i)
				{
					tmpData[i] = data[i];
				}
				currentCapacity = newCapacity;
				delete[] data;
				data = tmpData;
			}
		}
		data[currentSize++] = value;
	}


	void pop_back() {
		if (currentSize > 0) --currentSize;
	}

	int size() {
		return currentSize;
	}

	int capacity() {
		return currentCapacity;
	}


	void resize(int newCapacity) {
		if (newCapacity < 0) {
			cout << "양수를 입력하세요";
			return;
		}

		T* tmpData = new T[newCapacity];

		int tmp = (newCapacity < currentSize) ? newCapacity : currentSize; // newCapacity가 원래 size보다 작은 경우 처리

		for (int i = 0; i < tmp; i++) {
			tmpData[i] = data[i];
		}

		delete[] data;
		data = tmpData;

		currentSize = tmp;
		currentCapacity = newCapacity;
	}

	void sortData() {
		// 오름차순 정렬
		sort(data, data + currentSize);
	}

	void print() {
		cout << "현재 원소 : ";
		for (int i = 0; i < currentSize; i++) {
			cout << data[i] << "  ";
		}
		cout << endl;
	}
};



int main() {
	SimpleVector<int> vector1;

	vector1.push_back(10);
	vector1.push_back(30);
	vector1.push_back(50);
	vector1.pop_back();
	vector1.push_back(70);

	vector1.print();

	cout << "size :" << vector1.size() << ", capacity :" << vector1.capacity() << endl;

	cout << endl << "- - - - - - - - - - - -" << endl;
	SimpleVector<string> vector2(5);
	vector2.push_back("안녕");
	vector2.push_back("하세요");
	vector2.push_back("테스트");
	vector2.push_back("삭제");
	vector2.pop_back();
	vector2.push_back("입니다.");

	vector2.print();
	cout << "size :" << vector2.size() << ", capacity :" << vector2.capacity() << endl;

	vector2.push_back("벡터 크기를 늘려볼게요.");
	vector2.push_back("얍!");
	vector2.print();
	cout << "size :" << vector2.size() << ", capacity :" << vector2.capacity() << endl;
	cout << "벡터 정렬" << endl;
	vector2.sortData();
	vector2.print();
	cout << "벡터 사이즈 변경" << endl;
	vector2.resize(5);
	cout << "size :" << vector2.size() << ", capacity :" << vector2.capacity() << endl;
	vector2.print();
	return 0;
}

profile
누군가에게 추억을 만들어주는 그날까지

0개의 댓글