[C++] 명품 C++ 프로그래밍 10장 실습문제 풀이
10장 템플릿과 표준 라이브러리(STL)
1번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
template <class T>
T biggest(T x[], int size){
T biggest = x[0];
for(int i = 1 ; i < size ; i++){
if(biggest < x[i]){
biggest = x[i];
}
}
return biggest;
}
int main(){
int x[] = {1,10,100,5,4};
cout << biggest(x,5)<<endl;
}
2번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
template <class T>
bool equalArrays(T x[], T y[], int size){
for(int i = 0 ; i < size ; i ++){
if(x[i] != y[i]){
return false;
}
}
return true;
}
int main(){
int x[] = {1,10,100,5,4};
int y[] = {1,10,100,5,4};
if(equalArrays(x,y,5))
cout<<"같다"<<endl;
else
cout<<"다르다"<<endl;
}
3번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
template <class T>
bool reverseArrays(T x[], int size){
for(int i = 0 ; i < size / 2 ; i ++){
T tmp = x[size - i];
x[size - i] = x[i];
x[i] = tmp;
}
}
int main(){
int x[] = {1,10,100,5,4};
reverseArrays(x,5);
for(int i = 0 ; i < 5 ; i ++)
cout<<x[i]<<' ';
cout<<endl;
}
4번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
template <class T>
bool search(T data, T x[], int size){
for(int i = 0 ; i < size ; i ++){
if(x[i] != data){
return true;
}
}
return false;
}
int main(){
int x[] = {1,10,100,5,4};
if(search(100,x,5))
cout<<"100이 배열 x에 포함되어 있다."<<endl;
else
cout<<"100이 배열 x에 포함되어 있지 않다."<<endl;
}
5번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
template <class T>
T * concat(T a[], int sizeA, T b[], int sizeB){
T * newArr = new T[sizeA + sizeB];
for(int i = 0 ; i < sizeA ; i ++)
newArr[i] = a[i];
for(int i = sizeA ; i < sizeA+sizeB ; i ++)
newArr[i] = b[i - sizeA];
return newArr;
}
int main() {
cout << "정수 5개를 입력하라. 배열 x에 삽입한다 >> ";
int x[5];
for (int i = 0; i < 5; i++)
cin >> x[i];
cout << "정수 5개를 입력하라. 배열 y에 삽입한다 >> ";
int y[5];
for (int i = 0; i < 5; i++)
cin >> y[i];
cout << "합친 정수 배열을 출력한다." << endl;
int* z = concat(x, 5, y, 5);
for (int i = 0; i < 10; i++)
cout << z[i] << ' ';
cout << endl;
}
6번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
using namespace std;
template <class T>
T* remove(T a[], int sizeA, T b[], int sizeB, int& retSize) {
T* tmp = new T[sizeA];
int count = 0;
for (int i = 0; i < sizeA; i++) {
bool flag = true;
for (int j = 0; j < sizeB; j++) {
if (a[i] == b[j]) {
flag = false;
break;
}
}
if (flag)
tmp[count++] = a[i];
}
retSize = count;
T* newArr = new T[count];
for (int i = 0; i < count; i++)
newArr[i] = tmp[i];
delete[]tmp;
return newArr;
}
int main() {
cout << "정수 5개를 입력하라. 배열 x에 삽입한다 >> ";
int x[5];
for (int i = 0; i < 5; i++)
cin >> x[i];
cout << "정수 5개를 입력하라. 배열 y에 삽입한다 >> ";
int y[5];
for (int i = 0; i < 5; i++)
cin >> y[i];
int size = 0;
int* p = remove(x, 5, y, 5, size);
cout << "배열 x[]에서 y[]를 뺀 결과를 출력한다. 개수는 " << size << endl;
for (int i = 0; i < size; i++)
cout << p[i] << ' ';
cout << endl;
}
7번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;
class Circle {
int radius;
public:
Circle(int radius = 1) { this->radius = radius; }
int getRadius() { return radius; }
bool operator>(Circle& op2) { // 해결 방법 #1
if (this->radius > op2.radius)
return true;
else
return false;
}
};
template <class T>
T bigger(T a, T b) {
if (a > b)
return a;
else
return b;
}
Circle bigger(Circle& op1, Circle& op2) { // 해결 방법 #2
if (op1.getRadius() > op2.getRadius())
return op1;
else
return op2;
}
int main() {
int a = 20, b = 50, c;
c = bigger(a, b);
cout << "20과 50중 큰 값은 " << c << endl;
Circle waffle(10), pizza(20), y;
y = bigger(waffle, pizza);
cout << "waffle과 pizza중 큰 것의 반지름은 " << y.getRadius() << endl;
}
8번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
using namespace std;
class Comparable {
public:
virtual bool operator>(Comparable& op2) = 0;
virtual bool operator<(Comparable& op2) = 0;
virtual bool operator==(Comparable& op2) = 0;
};
class Circle : public Comparable {
int radius;
public:
Circle(int radius = 1) { this->radius = radius; }
int getRadius() { return radius; }
virtual bool operator>(Comparable& op2) {
Circle& tmp = (Circle&)op2;
if (this->radius > tmp.radius)
return true;
else
return false;
}
virtual bool operator<(Comparable& op2) {
Circle& tmp = (Circle&)op2;
if (this->radius < tmp.radius)
return true;
else
return false;
}
virtual bool operator==(Comparable& op2) {
Circle& tmp = (Circle&)op2;
if (this->radius == tmp.radius)
return true;
else
return false;
}
};
template <class T>
T bigger(T a, T b) {
if (a > b)
return a;
else
return b;
}
int main() {
int a = 20, b = 50, c;
c = bigger(a, b);
cout << "20과 50중 큰 값은 " << c << endl;
Circle waffle(10), pizza(20), y;
y = bigger(waffle, pizza);
cout << "waffle과 pizza중 큰 것의 반지름은 " << y.getRadius() << endl;
}
다운 캐스팅 유의 해야함
9번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vt;
double sum = 0;
int data;
while (true) {
cout << "정수를 입력하세요(0을 입력하면 종료) >> ";
cin >> data;
if (data == 0)
break;
sum += data;
vt.push_back(data);
for (auto& a : vt)
cout << a << ' ';
cout << endl << "평균 = " << sum / vt.size() << endl;
}
}
10번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
class Nation {
string country, capital;
public:
Nation(string country, string capital) {
this->country = country;
this->capital = capital;
}
string getCountry() { return country; }
string getCapital() { return capital; }
};
class NationManager {
vector<Nation> vt;
int getMenu() {
int selectMenu;
cout << "정보 입력: 1, 퀴즈: 2, 종료: 3 >> ";
cin >> selectMenu; cin.ignore();
return selectMenu;
}
void insert() {
string country, capital;
cout << "현재 " << vt.size() << "개의 나라가 입력되어 있습니다" << endl;
cout << "나라와 수도를 입력하세요(no no 이면 입력 끝)" << endl;
while (true) {
cout << vt.size() + 1 << " >> ";
cin >> country >> capital;
if (country == "no" && capital == "no")
break;
bool flag = true;
for (auto& a : vt) {
if (a.getCountry() == country) {
flag = false;
break;
}
}
if (flag)
vt.push_back(Nation(country, capital));
else
cout << "already exists !!" << endl;
}
}
void quiz() {
string answer;
while (true) {
int n = rand() % vt.size();
cout << vt[n].getCountry() << "의 수도는? ";
cin >> answer;
if (answer == "exit")
break;
if (vt[n].getCapital() == answer)
cout << "Correct !!" << endl;
else
cout << "NO !!" << endl;
}
}
public:
NationManager() { srand((unsigned)time(0)); }
void run() {
cout << "***** 나라의 수도 맞추기 게임을 시작합니다 *****" << endl;
int flag = true;
while (flag) {
switch (getMenu()) {
case 1:
insert();
break;
case 2:
quiz();
break;
case 3:
flag = false;
break;
default:
cout << "다시 입력하세요" << endl;
break;
}
}
cout << "***** 나라의 수도 맞추기 게임을 종료합니다 *****" << endl;
}
};
int main() {
NationManager NM;
NM.run();
}
11번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Book {
string year, title, writer;
public:
Book(string year, string title, string writer) {
this->year = year;
this->title = title;
this->writer = writer;
}
string getYear() { return year; }
string getTitle() { return title; }
string getWriter() { return writer; }
void show() { cout << year << "년도, " << title << ", " << writer << endl; }
};
class BookManager {
vector<Book> vt;
void searchByWriter() {
string writer;
bool flag = false;
cout << "검색하고자 하는 저자 이름을 입력하세요 >> "; getline(cin, writer);
for (auto& a : vt) {
if (a.getWriter() == writer) {
a.show();
flag = true;
}
}
if (!flag)
cout << writer << "저자의 책이 없습니다." << endl;
}
void SearchByYear() {
string year;
bool flag = false;
cout << "검색하고자 하는 년도를 입력하세요 >> "; getline(cin, year);
for (auto& a : vt) {
if (a.getYear() == year) {
a.show();
flag = true;
}
}
if (!flag)
cout << year << "년도의 책이 없습니다." << endl;
}
public:
void run() {
string year, title, writer;
cout << "입고할 책을 입력하세요. 년도에 -1을 입력하면 입고를 종료합니다." << endl;
while (true) {
cout << "년도 >> "; getline(cin, year);
if (year == "-1")
break;
cout << "책이름 >> "; getline(cin, title);
cout << "저자 >> "; getline(cin, writer);
vt.push_back(Book(year, title, writer));
}
cout << "총 입고된 책은 " << vt.size() << "권입니다." << endl;
searchByWriter();
SearchByYear();
}
};
int main() {
BookManager BM;
BM.run();
}
12번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
class EnglishWord {
string eng, kor;
public:
EnglishWord(string eng, string kor) {
this->eng = eng;
this->kor = kor;
}
string getEnglish() { return eng; }
string getKorean() { return kor; }
};
class EnglishWordTestManager {
vector<EnglishWord> vt;
void shuffle() {
for (int i = 0; i < 1000; i++) {
int r1 = rand() % vt.size();
int r2 = rand() % vt.size();
EnglishWord tmp = vt[r1];
vt[r1] = vt[r2];
vt[r2] = tmp;
}
}
int getMenu() {
int selectMenu;
cout << "어휘 삽입: 1, 어휘 테스트: 2, 프로그램 종료: 그 외 키 >> ";
cin >> selectMenu; cin.ignore();
return selectMenu;
}
void insert() {
string eng, kor;
cout << "영어 단어에 exit을 입력하면 입력 끝" << endl;
while (true) {
cout << "영어 >> "; getline(cin, eng);
if (eng == "exit")
break;
cout << "한글 >> "; getline(cin, kor);
vt.push_back(EnglishWord(eng, kor));
}
}
void test() {
cout << "영어 어휘 테스트를 시작합니다. 1~4외 다른 입력시 종료." << endl;
int answer;
while (true) {
shuffle();
int n = rand() % 4;
cout << vt[n].getEnglish() << "?" << endl;
for (int i = 0; i < 4; i++)
cout << "(" << i + 1 << ") " << vt[i].getKorean() << ' ';
cout << ": >> "; cin >> answer;
if (answer < 1 || answer > 4)
break;
if (answer == n + 1)
cout << "Correct !!" << endl;
else
cout << "No. !!"<<endl;
}
}
public:
EnglishWordTestManager() { srand((unsigned)time(0)); }
void run() {
cout << "***** 영어 어휘 테스트를 시작합니다. *****" << endl;
bool flag = true;
while (flag) {
switch (getMenu()) {
case 1:
insert();
break;
case 2:
test();
break;
default:
flag = false;
break;
}
cout << endl;
}
cout << "***** 영어 어휘 테스트를 종료합니다. *****" << endl;
}
};
int main() {
EnglishWordTestManager EWTM;
EWTM.run();
}
13번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
#include <map>
using namespace std;
class ScoreManager {
map<string, int> scores;
int getMenu() {
int selectMenu;
cout << "입력:1, 조회:2, 종료:3 >> ";
cin >> selectMenu; cin.ignore();
return selectMenu;
}
void insert() {
string name;
int score;
cout << "이름과 점수 >> ";
cin >> name >> score; cin.ignore();
scores[name] = score;
}
void search() {
string name;
cout << "이름 >> ";
cin >> name;
if (scores.find(name) == scores.end())
cout << name << " 학생은 존재하지 않습니다" << endl;
else
cout << name << "의 점수는 " << scores[name] << endl;
}
public:
void run() {
cout << "***** 점수 관리 프로그램 HIGH SCORE을 시작합니다. *****" << endl;
bool flag = true;
while (flag) {
switch (getMenu()) {
case 1:
insert();
break;
case 2:
search();
break;
case 3:
flag = false;
break;
}
}
cout << "프로그램을 종료합니다..." << endl;
}
};
int main() {
ScoreManager SM;
SM.run();
}
14번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <string>
#include <map>
using namespace std;
class PasswordManager {
map<string, string> pwds;
int getMenu() {
int selectMenu;
cout << "삽입:1, 검사:2, 종료:3 >> ";
cin >> selectMenu; cin.ignore();
return selectMenu;
}
void insert() {
string name, password;
cout << "이름 암호 >> ";
cin >> name >> password;
pwds[name] = password;
}
void confirm() {
string name, password;
cout << "이름 >> ";
cin >> name;
if (pwds.find(name) == pwds.end())
cout << name << " 회원은 존재하지 않습니다" << endl;
else {
while (true) {
cout << "암호 >> ";
cin >> password;
if (pwds[name] == password) {
cout << "통과 !!" << endl;
return;
}
else
cout << "실패~~" << endl;
}
}
}
public:
void run() {
cout << "***** 암호 관리 프로그램 WHO를 시작합니다. *****" << endl;
bool flag = true;
while (flag) {
switch (getMenu()) {
case 1:
insert();
break;
case 2:
confirm();
break;
case 3:
flag = false;
break;
}
}
cout << "프로그램을 종료합니다..." << endl;
}
};
int main() {
PasswordManager PM;
PM.run();
}
15번
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Circle {
string name;
int radius;
public:
Circle(int radius, string name) {
this->radius = radius;
this->name = name;
}
double getArea() { return 3.14 * radius * radius; }
string getName() { return name; }
};
class CircleManager {
vector<Circle*> CircleVt;
int getMenu() {
int selectMenu;
cout << "삽입:1, 삭제:2, 모두보기:3, 종료:4 >> ";
cin >> selectMenu; cin.ignore();
return selectMenu;
}
void insert() {
string name;
int radius;
cout << "생성하고자 하는 원의 반지름과 이름은 >> ";
cin >> radius >> name;
CircleVt.push_back(new Circle(radius, name));
}
void remove() {
string name;
cout << "삭제하고자 하는 원의 이름은 >> ";
cin >> name;
auto it = CircleVt.begin();
while (it != CircleVt.end()) {
if ((*it)->getName() == name) {
Circle* tmp = *it;
it = CircleVt.erase(it);
delete tmp;
}
else
it++;
}
}
void showAll() {
for (auto& c : CircleVt)
cout << c->getName() << endl;
cout << endl;
}
public:
void run() {
cout << "원을 삽입하고 삭제하는 프로그램입니다." << endl;
bool flag = true;
while (flag) {
switch (getMenu()) {
case 1:
insert();
break;
case 2:
remove();
break;
case 3:
showAll();
break;
case 4:
flag = false;
break;
}
}
cout << "프로그램을 종료합니다..." << endl;
}
};
int main() {
CircleManager CM;
CM.run();
}
16번
Shape.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef SHAPE_H
#define SHAPE_H
#include <iostream>
using namespace std;
class Shape {
protected:
virtual void draw() = 0;
public:
void paint();
virtual ~Shape() {}
};
#endif
Shape.cpp
1
2
3
4
#include "Shape.h"
void Shape::paint() {
draw();
}
Line.h
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef LINE_H
#define LINE_H
#include "Shape.h"
class Line : public Shape {
protected:
virtual void draw();
public:
virtual ~Line() {}
};
#endif
Line.cpp
1
2
#include "Line.h"
void Line::draw() { cout << "Line" << endl; }
Rect.h
1
2
3
4
5
6
7
8
9
10
11
#ifndef RECT_H
#define RECT_H
#include "Shape.h"
class Rect : public Shape {
protected:
virtual void draw();
public:
virtual ~Rect() {}
};
#endif
Rect.cpp
1
2
#include "Rect.h"
void Rect::draw() { cout << "Rectangle" << endl; }
Circle.h
1
2
3
4
5
6
7
8
9
10
11
#ifndef CIRCLE_H
#define CIRCLE_H
#include "Shape.h"
class Circle : public Shape {
protected:
virtual void draw();
public:
virtual ~Circle() {}
};
#endif
Circle.cpp
1
2
#include "Circle.h"
void Circle::draw() { cout << "Circle" << endl; }
GraphicEditor.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef GRAPHICEDITOR_H
#define GRAPHICEDITOR_H
#include <vector>
#include "Circle.h"
#include "Rect.h"
#include "Line.h"
class GraphicEditor {
vector<Shape*> shapeVt;
int getMenu();
int getShape();
void insert();
void remove();
void show();
public:
void run();
};
#endif
GraphicEditor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "GraphicEditor.h"
int GraphicEditor::getMenu() {
int selectMenu;
cout << "삽입:1, 삭제:2, 모두보기:3, 종료:4 >> ";
cin >> selectMenu; cin.ignore();
return selectMenu;
}
int GraphicEditor::getShape() {
int selectShape;
cout << "선:1, 원:2, 사각형:3 >> ";
cin >> selectShape; cin.ignore();
return selectShape;
}
void GraphicEditor::insert() {
switch (getShape()) {
case 1:
shapeVt.push_back(new Line());
break;
case 2:
shapeVt.push_back(new Circle());
break;
case 3:
shapeVt.push_back(new Rect());
break;
}
}
void GraphicEditor::remove() {
int selectIndex;
cout << "삭제고자 하는 도형의 인덱스 >> ";
cin >> selectIndex; cin.ignore();
int count = 0;
auto it = shapeVt.begin();
while (it != shapeVt.end()) {
if (count == selectIndex) {
Shape* tmp = (*it);
it = shapeVt.erase(it);
delete tmp;
}
else
it++;
count++;
}
}
void GraphicEditor::show() {
int count = 0;
for (auto& s : shapeVt) {
cout << count++ << " : ";
s->paint();
}
}
void GraphicEditor::run() {
cout << "그래픽 에디터입니다." << endl;
bool flag = true;
while (flag) {
switch (getMenu()) {
case 1:
insert();
break;
case 2:
remove();
break;
case 3:
show();
break;
case 4:
flag = false;
break;
}
}
cout << "프로그램을 종료합니다..." << endl;
}
main.cpp
1
2
3
4
5
#include "GraphicEditor.h"
int main() {
GraphicEditor GE;
GE.run();
}
This post is licensed under CC BY 4.0 by the author.