251218 TIL - C++ 9일차
2025. 12. 18. 20:54ㆍ언리얼 7기 본캠프
오늘은 STL에 대한 기초 내용들과 간단한 용법에 대해서 배웠음
STL에 대해 더 많은 정보를 찾아보려고 여기저기 둘러보니까 지금 배우는것들 말고도 어마어마한 양의 내용들이 나오는데...
추후 이것들을 다 흡수할 수 있었으면 좋겠음
오늘은 그동안 배운것들을 토대로 과제를 만들어달라고 AI에게 요청함. 과제와 코드를 첨부함
1️⃣ 주제: STL (vector, map, algorithm)
[초급] 과제 1: 숫자 저장소 (vector 기초)
- vector<int>를 하나 만드세요.
- 사용자에게 정수 5개를 입력받아 벡터에 push_back으로 넣으세요.
- 반복문(for)을 사용해 벡터에 들어있는 모든 숫자를 출력하세요.
[중급] 과제 2: 과일 가격표 (map 기초)
- map<string, int>를 만드세요.
- "Apple"은 1000원, "Banana"는 2000원, "Grape"는 3000원으로 데이터를 넣으세요. (insert 또는 [] 사용)
- 사용자에게 과일 이름을 입력받고, 그 과일의 가격을 출력하세요. (없는 과일이면 0원 혹은 "없음" 출력)
[고급] 과제 3: 거꾸로 정렬하기 (sort 응용)
- vector<int>에 10, 50, 20, 40, 30을 넣으세요.
- <algorithm> 헤더의 sort 함수를 사용하여 이 숫자들을 **오름차순(작은 순)**으로 정렬해 출력하세요.
- 그다음, **내림차순(큰 순)**으로 정렬하여 다시 출력해보세요.
- 힌트: sort(v.begin(), v.end())는 오름차순이고, 내림차순은 rbegin(), rend()를 쓰거나 greater<int>()를 추가로 넣으면 됩니다.
2️⃣ 주제: 메모리 관리 & 스마트 포인터
[초급] 과제 4: 수동 관리의 귀찮음 (new/delete)
- int* ptr 변수를 선언하세요.
- new를 사용해 힙 메모리에 정수 하나를 할당하고 값 100을 넣으세요.
- 값을 출력한 뒤, 반드시 delete를 이용해 메모리를 해제하세요. (이걸 안 하면 메모리 누수!)
[중급] 과제 5: 독점하는 포인터 (unique_ptr)
- <memory> 헤더를 사용하세요.
- unique_ptr<int>를 만들어 make_unique로 숫자 777을 저장하세요.
- move 함수를 사용하여 이 포인터의 소유권을 다른 unique_ptr 변수로 옮기세요.
- 옮긴 후, 원래 변수가 비어있는지(nullptr) 확인하는 if문을 작성하세요.
[고급] 과제 6: 같이 쓰는 포인터 (shared_ptr)
- shared_ptr<int> 변수 p1을 만들고 숫자 10을 저장하세요.
- p2라는 변수를 만들어 p1을 그냥 대입하세요. (p2 = p1)
- p1.use_count()를 출력하여 현재 몇 명이 공유하고 있는지(2명이어야 함) 확인하세요.
- p1.reset()을 한 뒤, 다시 카운트(1명이어야 함)를 확인해보세요.
3️⃣ 주제: 템플릿 & 오버로딩
[초급] 과제 7: 같은 이름 다른 기능 (함수 오버로딩)
- 함수 이름은 둘 다 printData로 하세요.
- 첫 번째 함수는 int를 받아 "정수: [값]"을 출력합니다.
- 두 번째 함수는 string을 받아 "문자열: [값]"을 출력합니다.
- 메인 함수에서 printData(10)과 printData("Hello")를 호출해 잘 구분되는지 확인하세요.
[중급] 과제 8: 만능 덧셈기 (함수 템플릿)
- template <typename T>를 사용해 add(T a, T b) 함수를 만드세요.
- 이 함수는 두 값을 더해서 리턴합니다.
- 메인 함수에서 int 끼리 더하기(1+2), double 끼리 더하기(1.5+2.5)가 모두 잘 되는지 확인하세요.
[고급] 과제 9: 만능 보관함 (클래스 템플릿)
- 무엇이든 하나 담을 수 있는 클래스 Container<T>를 만드세요.
- 멤버 변수로 T data를 가집니다.
- setData(T value)로 값을 넣고, getData()로 값을 반환하는 기능을 만드세요.
- Container<char>를 만들어 문자 'A'를 저장하고 꺼내보세요.
🏆 [종합] 과제 10: "미니 RPG 캐릭터 관리"
목표: 배운 내용을 종합하여 캐릭터 파티를 관리해봅시다.
- 클래스 생성: Character 클래스를 만드세요. (멤버: 이름string, 레벨int)
- 생성자에서 이름과 레벨을 입력받습니다.
- introduce() 함수를 만들어 "저는 [이름], 레벨 [N]입니다."를 출력하게 하세요.
- 스마트한 저장소: vector<unique_ptr<Character>> 타입의 party 변수를 만드세요. (포인터를 담는 벡터입니다!)
- 캐릭터 추가: make_unique를 사용하여 "Warrior"(Lv10), "Mage"(Lv5) 두 캐릭터를 생성해 party 벡터에 넣으세요.
- 전체 출력: 반복문(for)을 돌면서 파티에 있는 모든 캐릭터의 introduce() 함수를 호출하세요.
- 힌트: 벡터 안의 요소가 포인터이므로 ->introduce()로 호출해야 합니다.
//반복자 for 학습
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> vect = { "가", "나", "다", "라", "마", "바" };
for (int i = 0; i < vect.size(); i++) { // 결과 : 가나다라마바
cout << vect[i];
}
cout << endl;
for (auto& ve : vect) { // 결과 : 가나다라마바
cout << ve;
}
//cout << vect; <- 컴파일 에러. cout은 벡터 전체를 출력할 수 없음.
return 0;
}
// AI 과제 1
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<int> number;
while (number.size() < 5) {
int input;
cout << "숫자를 입력해주세요 : ";
cin >> input;
number.push_back(input);
}
for (int i = 0; i < number.size(); i++) {
cout << number[i] << " ";
}
return 0;
}
//AI 과제 2
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
map<string, int> fruit;
fruit["Apple"] = 1000;
fruit["Banana"] = 2000;
fruit["Grape"] = 3000;
string fruitName;
cout << "가격을 확인할 과일명을 입력해주세요(Apple, Banana, Grape) : ";
cin >> fruitName;
auto it = fruit.find(fruitName);
if (it != fruit.end()) {
cout << it->first << "의 가격은 " << it->second << "원 입니다.";
}
else {
cout << "그런 이름의 과일은 없습니다.";
}
return 0;
}
//AI 과제 3
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> number = { 10, 50, 20, 40, 30 };
sort(number.begin(), number.end());
for (int i = 0; i < number.size(); i++) {
cout << number[i] << " ";
}
cout << endl;
sort(number.rbegin(), number.rend());
for (int i = 0; i < number.size(); i++) {
cout << number[i] << " ";
}
}
//AI 과제 4
#include <iostream>
using namespace std;
int main() {
int* ptr;
ptr = new int(100);
cout << *ptr << endl;
delete ptr;
return 0;
}
//AI 과제 5
#include <iostream>
#include <memory>
using namespace std;
int main() {
unique_ptr<int> ptr1 = make_unique<int>(777);
unique_ptr<int> ptr2 = move(ptr1);
if (ptr1 == nullptr) {
cout << "ptr1이 비었습니다." << endl;
}
cout << "ptr2 : " << *ptr2 << endl;
return 0;
}
//AI 과제 6
#include <iostream>
#include <memory>
using namespace std;
int main() {
shared_ptr<int> p1 = make_shared<int>(10);
shared_ptr<int> p2 = p1;
cout << "p1 사용 수 : " << p1.use_count() << endl;
p1.reset();
cout << "리셋 후 p1 사용 수 : " << p1.use_count() << endl;
cout << "리셋 후 p2 사용 수 : " << p2.use_count() << endl;
return 0;
}
//AI 과제 7
#include <iostream>
#include <string>
using namespace std;
void printData(int a) {
cout << "int입력 printData : " << a << endl;
}
void printData(string b) {
cout << "string입력 printData : " << b << endl;
}
int main() {
printData(10);
printData("Hello");
return 0;
}
//AI 과제 8
#include <iostream>
using namespace std;
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int a = 1;
int b = 2;
double c = 1.5;
double d = 2.5;
cout << "int형 덧셈 결과 : " << add(a, b) << endl;
cout << "double형 덧셈 결과 : " << add(c, d) << endl;
return 0;
}
//AI 과제 9
#include <iostream>
using namespace std;
template <typename T>
class Container {
T data[100];
int size;
public:
Container() : size(0) {}
void setdata(T value) {
if (size < 100) {
data[size++] = value;
}
else {
cout << "저장 공간이 가득 찼습니다." << endl;
}
}
T getdata(int index) {
if (index < 0 || index >= size) {
cout << "잘못된 index값 입니다." << endl;
return T();
}
return data[index];
}
int getSize() {
return size;
}
};
int main() {
Container<char> cont;
cont.setdata('A');
cout << cont.getdata(0) << endl;
return 0;
}
//AI 과제 10
#include <iostream>
#include <string>
#include <memory>
#include <vector>
using namespace std;
class Character {
string name;
int level;
public:
Character(string a, int b) {
name = a;
level = b;
}
void introduce() {
cout << "저는 " << name << "입니다. 저의 레벨은 " << level << "입니다." << endl;
}
};
int main() {
vector<unique_ptr<Character>> party;
unique_ptr<Character> Warrior = make_unique<Character>("Warrior", 10);
unique_ptr<Character> Mage = make_unique<Character>("Mage", 5);
party.push_back(move(Warrior));
party.push_back(move(Mage));
for (const auto& a : party) {
a->introduce();
}
return 0;
}'언리얼 7기 본캠프' 카테고리의 다른 글
| 251222 TIL - C++ 11일차 (0) | 2025.12.22 |
|---|---|
| 251219 TIL - C++ 10일차 (0) | 2025.12.19 |
| 251217 TIL - C++ 8일차 (0) | 2025.12.17 |
| 251216 TIL - C++ 7일차, 새로운 과제 하달 (1) | 2025.12.16 |
| 251215TIL - C++ 6일차 - 과제 제출 (0) | 2025.12.15 |