반응형

7.9> 통계를 내는 Statistics 클래스를 만들려고 한다. 데이터는 Statistics 클래스 내부에 int 배열을 동적으로 할당받아 유지한다. 다음과 같은 연산이 잘 이루어지도록 Statistics 클래스와 !, >>, <<, ~ 연산자 함수를 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class Statistics{

private:

        int size; //동적 배열의 사이즈

        int index; //마지막 원소의 인덱스

        int *p; //동적 배열을 가리킬 포인터

public:

        Statistics(int size=5,int index=-1); //기본 사이즈 5, 인덱스 -1(nothing)

        friend bool operator!(Statistics op);

        void operator>>(int &op);

        Statistics& operator<<(int op);

        void operator~();

       

};

Statistics::Statistics(int size,int index){

        this->size=size;

        this->index=index;

        p=new int[size]; //size 크기만큼의 int 동적 배열 할당

}

 

bool operator!(Statistics op){

        if(op.index==-1) //index -1이면 true 반환

               return true;

        else

               return false;

}

void Statistics::operator>>(int &op){ //평균구하는 함수

        int sum=0;

        for(int i=0;i<index+1;i++){sum+=p[i];} //실제 원소 개수는 index+1 (0부터시작하니까)

        op= sum/(index+1); //op 평균값 넣어줌(참조라서 원본 바뀜)

}

Statistics& Statistics::operator<<(int op){

        index++; //인덱스 증가

        if(size<=index){ //인덱스를 하나키웠는데 size 크기 같으면 배열 크기보다 원소가 많은 경우

               int *tmp=new int[size+5]; //하나씩 키우면 자주 없앴다 만들었다 해야하니 5개씩 늘린다.

               for(int i=0;i<size;i++){ //(size+5 하면 p크기가 size라서 오류날 있음)

                       tmp[i]=p[i]; //p 원소를 전부 tmp 복사

               }

               delete []p; //p 가리키는 동적배열 힙에 반환

               p=tmp; //tmp 가리키는 배열을 p 가리키게 (어차피 tmp 사라지므로 깊은 복사 필요 없음)

               size+=5; //size 5 추가

        }

        p[index]=op; //index 오퍼랜드 대입

        return *this; //현재 객체의 참조 리턴(이름)

}

void Statistics::operator~(){ //전부 출력하는 함수

        for(int i=0;i<index+1;i++){ //원소 개수 = index+1

               cout<<p[i]<<" ";

        }

        cout<<endl;

}

 

int main(void){

        Statistics stat;

        if(!stat) cout<<"현재 통계 데이타가 없습니다."<<endl;

        int x[5];

        cout <<"5 개의 정수를 입력하라>>";

        for(int i=0;i<5;i++) cin >> x[i]; //x[i] 정수 입력

        for(int i=0;i<5;i++) stat << x[i]; //x[i] 값을 통계 객체에 삽입한다.

        stat << 100 << 200; //100, 200 통계 객체에 삽입한다.

        ~stat; //통계 데이타를 모두 출력한다.

 

        int avg;

        stat>>avg; //통계 객체로부터 평균을 받는다.

        cout<<"avg="<<avg<<endl; //평균을 출력한다.

        return 0;

}

 

<결과창>

               

                    


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

MyQueue Class  (0) 2017.12.31
Stack class  (0) 2017.12.25
Circle class 오퍼레이터 오버로딩  (0) 2017.12.25
Circle class  (0) 2017.12.25
Matrix class 활용, 연산자 오버로딩  (0) 2017.12.25
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
using namespace std;
 
int main(void){
 
    char c=3;
    int a=1;
    double d=1.0;
 
    char *p1=&c;
    int *p2=&a;
    double *p3=&d;
    cout<<"캐릭터 "<<(int)p1<<" "<<(int)(p1+1)<<endl//1->주소1증가
    cout<<"정수 "<<(int)p2<<" "<<(int)(p2+1)<<endl//1->주소4증가
    cout<<"실수(더블) "<<(int)p3<<" "<<(int)(p3+1)<<endl;//1->주소8증가
}
cs




char 포인터에 더하기 1을 하면 주소는 1이 증가
int 포인터에 더하기 1을 하면 주소는 4이 증가
double 포인터에 더하기 1을 하면 주소는 8이 증가
헷갈리지 말자




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
using namespace std;
 
int main(void){
 
    int a[2]={6,10};
    int *p=a; //포인터 p는 배열a의 첫번째 원소를 가리키는 포인터
    int &r=*a; //r은 a의 첫번째 원소의 참조
    int &r2=r; //r2는 r의 참조 (참조의 참조)
 
    cout<<a[0]<<endl//6
    cout<<*p<<endl//6
    cout<<r<<endl//6
    cout<<r+1<<endl//6+1=7
    cout<<a<<endl//주소
    cout<<&r<<endl//첫번째 원소의 주소 =a
    cout<<*(&r)<<endl//레퍼런스 주소의 역참조 = 6
    cout<<*(&r+1)<<endl//레퍼런스 주소에 1을 더한것의 역참조 = 10(2번째 원소)
    cout<<r2<<endl//r2는 r을 가리키므로 6
}
cs


포인터는 주소가 담기는 메모리가 할당 된다.

레퍼런스는 메모리 상의 특정 공간을 차지하는 것이 아니라 컴파일 시에

원래 레퍼런스가 참조하던 변수의 *(주소값)으로 대체되는 것이다.







반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
using namespace std;
 
int main(void){
    int a;
    int &b=a;
    int *c=&a;
    a=7;
    cout<<"a="<<a<<" b="<<b<<" *c="<<*c<<endl;
    cout<<"&a="<<&a<<" &b="<<&b<<" c="<<c<<endl;
 
    return 0;
}
cs






a는 int형 변수
b는 a의 별명(레퍼런스, 참조)
c는 a를 가리키는 포인터 변수
즉 a와 b와 *c는 같을 것이고
&a 와 &b와 c는 같을 것이다.
헷갈리지 말자~!


반응형
반응형

인하대학교 전자공학과 데이터 구조 포인터, 어레이 과제 (pointer, array)


인하대학교 전자공학과 데이터 구조 하노이의 탑, 이진 탐색(binary search, tir, recursive)


인하대학교 전자공학과 데이터 구조 시스템 스택, 선형 리스트 (system stack, linear list)


인하대학교 전자공학과 데이터 구조 preorder, postorder, max heap


인하대학교 전자공학과 데이터 구조 dfs, bfs, 프림, 크루스칼 (prim, kruskal)


소스코드, 수도코드, 플로우차트(순서도), 분석 및 고찰, 결과창 등이 들어있는 보고서입니다.


전부 만점받은 보고서입니다. 

반응형
반응형

1. Array : Let’s assume that we have the following declaration:

1.1. Please store the above data using scanf() function in two 2-dimension array, respectively. You can show the result.

 

1.2. Please create a new array ‘element[2][3]’ to obtain the sum of the value of First array and Second array. For example,

element[1][2] = First[1][2]+Second[1][2].

element[2][1] = First[2][1]+Second[2][1].




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
/*
    {{16,18,23},{54,91,11}}          {{24,52,77},{16,19,59}}
    1-1)Please store the above data using  function in two  2-dimension array, respectively. You can show the result.
    1-2)Please create a new array ‘Element[2][3]’ to obtain the sum of the value of First array and Second array. For example,
        Element[1][2] = First[1][2]+Second[1][2]. 
        Element[2][1] = First[2][1]+Second[2][1].
    ROW : 행 수 COL : 열 수
    array_input : 배열에 원소 값을 사용자가 입력할 수 있게 하는 함수
    array_print : 배열을 원소별로 출력해주는 함수
    array_sum   : 배열의 합을 구해주는 함수
    First[ROW][COL] : 2*3 사이즈의 2차원 배열1
    Second[ROW][COL] : 2*3 사이즈의 2차원 배열2
    Element[ROW][COL] : 2*3 사이즈의 2차원 배열, 동일한 위치의 First와 Second 의 원소의 합이 들어갈 배열
*/
#include <stdio.h>
#define ROW 2
#define COL 3
void array_input(int num,int array[][COL]);
void array_print(int num,int array[][COL]);
void array_sum(int array1[][COL],int array2[][COL],int array3[][COL]);
int main(void)
{
    int First[ROW][COL];
    int Second[ROW][COL];
    int Element[ROW][COL];
    array_input(1,First);
    array_input(2,Second);
    array_sum(First,Second,Element);
    printf("\n");
    array_print(1,First);
    printf("\n");
    array_print(2,Second);
    printf("\n");
    array_print(3,Element);
    return 0;
}
void array_input(int num,int array[][COL])
{
    int i;int j;
    printf("<%d번째 배열 입력>\n",num);
    for(i=0;i<ROW;i++)
    {
        for(j=0;j<COL;j++)
        {
        printf("%d번배열[%d][%d] 값 입력 : ",num,i,j);
        scanf("%d",&array[i][j]);
        }
    }
}
void array_print(int num,int array[][COL])
{
    int i;int j;
    for(i=0;i<ROW;i++)
    {
        for(j=0;j<COL;j++)
        {
        printf("%d번배열[%d][%d] : %d\n",num,i,j,array[i][j]);
        }
    }
}
void array_sum(int array1[][COL],int array2[][COL],int array3[][COL])
{
    int i;int j;
    for(i=0;i<ROW;i++)
    {
        for(j=0;j<COL;j++)
        {
        array3[i][j]=array1[i][j]+array2[i][j];
        }
    }
}
cs

 

 


2. Pointer : Let’s assume the next arrangement was declared. Calculate the final value of the following expression:

2.1. *(**p+3), *(**p+1), p[0], **(p[1]+1), *(p[1] +1)

2.2. *text, *(text+3), *(text+7)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
int main(void)
{
    char *p[3][2]={"abcd","efgh","ijklm","nop","qrstuv","wxyz"};
    char *text;
    char more[]="Happy Holidays";
    text=&more[4]; //'y'의 주소
    printf("*(**p+3)=%c\n",*(**p+3));
    printf("*(**p+1)=%c\n",*(**p+1));
    printf("p[0]=%x\n",p[0]);
    printf("**(p[1]+1)=%c\n",**(p[1]+1));
    printf("*(p[1]+1)=%x\n",*(p[1]+1));
    printf("\n");
    printf("*text=%c\n",*text);
    printf("*(text+3)=%c\n",*(text+3));
    printf("*(text+7)=%c\n",*(text+7));
}
cs







반응형
반응형

동적 메모리 할당을 이용하여서 사용자로부터 받은 주소록을 저장하고 출력하는 프로그램을 작성하라. 사용자로부터 먼저 주소의 개수를 입력받도록 하라. 주소의 많은 정보 중에서 이름과 휴대폰 번호만을 저장하도록 하자.


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
#include <stdio.h>
#include <stdlib.h>
#define SIZE 30
typedef struct BOOK
{
    char name[SIZE];
    char number[SIZE];
}book;
int main(void)
{
    int count=0;
    int i;
    book *p;
    printf("주소의 개수: ");
    scanf("%d",&count);
    getchar();
    p=(book*)malloc(count*sizeof(book));
    if(p==NULL)
    {
        printf("메모리할당오류\n");
        exit(1);
    }
    for(i=0;i<count;i++)
    {
        printf("이름을 입력하세요: ");
        gets(p[i].name);
        printf("휴대폰 번호를 입력하세요: ");
        gets(p[i].number);
    }
    printf("========================================\n");
    printf("이름\t휴대폰 번호\n");
    printf("========================================\n");
    for(i=0;i<count;i++)
    {
        printf("%s\t%s\n",p[i].name,p[i].number);
        printf("========================================\n");
    }
    free(p);
    return 0;
}
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C언어' 카테고리의 다른 글

양의 정수 저장  (0) 2017.02.22
단어 입력 받기  (0) 2017.02.21
문자열 동적 메모리  (0) 2017.02.21
양의 정수들의 합  (0) 2017.02.21
명령어 라인으로 텍스트 파일 합치기  (0) 2017.02.18

+ Recent posts