[C++] 구조체와 포인터 전달로 다항식 덧셈 알고리즘

C++ 로 만들어본 다항식 덧셈
#include <iostream>
#include <chrono>
using namespace std;
#define MAX(a, b) (((a) > (b)) ? (a) : (b))

#define MAX_Degree 101 //최대 항 개수

// 다항식의 항
typedef struct Term {
    int degree;   // 계수
    int exponent; // 지수
} term;

// 다항식 구조체
typedef struct Polynomial {
    int numTerm;         // 항의 개수
    term term[MAX_Degree]; // 각 항을 저장할 배열
} poly;

// 다항식 출력 함수
void printPoly(poly* p) {
    for (int i = 0; i < p->numTerm; i++) {
        int degree = p->term[i].degree;
        int exponent = p->term[i].exponent;

        // 계수가 0인 항은 생략
        if (degree == 0) continue;

        // 첫 항은 부호를 붙이지 않음
        if (i > 0) {
            if (degree > 0) cout << " + ";
            else if (degree < 0) cout << " - ";
        }
        else if (degree < 0) {
            cout << "-";
        }

        // 계수 출력
        if (abs(degree) != 1 || exponent == 0) {
            cout << abs(degree);
        }

        // 지수에 따른 x^n 출력
        if (exponent != 0) {
            cout << "x";
            if (exponent != 1) cout << "^" << exponent;
        }
    }
    cout << endl;
}


poly add_Poly(const poly* p1,const poly* p2) {
    poly result;
    result.numTerm = 0;

    int i = 0, j = 0;
    while (i < p1->numTerm && j < p2->numTerm) {
        if (p1->term[i].exponent == p2->term[j].exponent) {
            result.term[result.numTerm].degree = p1->term[i].degree + p2->term[j].degree; //계수더하기
            result.term[result.numTerm].exponent = p1->term[i].exponent; //지수값 그대로 넣기
            i++;
            j++;
        }
        else if (p1->term[i].exponent > p2->term[j].exponent) { //지수가 p1이 더 클경우
            result.term[result.numTerm] = p1->term[i];
            i++;
        }
        else { //지수가 p2가 더 클경우
            result.term[result.numTerm] = p2->term[j];
            j++;
        }
        result.numTerm++; //result 다음항으로
    }

    // 남은 항 추가 (p1 또는 p2에 남은 항이 있을 경우)
    while (i < p1->numTerm) {
        result.term[result.numTerm++] = p1->term[i++];
    }
    while (j < p2->numTerm) {
        result.term[result.numTerm++] = p2->term[j++];
    }

    return result;
}

int main() {
    // 다항식 초기화
    poly pol_1 = { 6, {{5, 5}, {-4, 4}, {3, 3}, {-2, 2}, {1, 1}, {-1, 0} }};

    // 결과 출력
    cout << "다항식: ";
    printPoly(&pol_1);

    // 다항식 초기화 (5x^5 + 4x^3 + 3x^2 -1)
    poly pol_2 = { 4, {{5, 5}, {4, 3},{3,2},{2,0}} };
    // 결과 출력
    cout << "다항식: ";
    printPoly(&pol_2);

    // 두 다항식의 합을 계산
    poly result = add_Poly(&pol_1, &pol_2);
    cout << "다항식 합: ";
    printPoly(&result);

    return 0;
}

 

Polynomial 구조체

다항식의 구조체

항의 개수 : numTerm

각 항의 계수와 지수를 Term구조체로 배열화한 배열

Term 구조체

각 항의 계수와 지수를 표현하는 구조체

 

 

Main함수에서 출력과 덧셈을 Polynomial구조체의 메모리 주소로 전달하여 각 함수에서는 포인터(*)로 받아 해당 구조체의 메모리 주소를 전달.

 

포인터 변수는 메모리의 주소를 저장하는 변수이기 때문에

함수 안에서 구조체의 변수에 참조하기 위해서 ->로 매개변수로 받아온 포인터가 가리키는 실제 객체에 참조시킨다.

 

.은 객체를 전달받아 왔을때 메모리에 저장된 값에 직접 접근 시키며

->는 포인터가 가리키는 실제 객체로 접근시킴

예시로 ptr이 포인터 변수라는 가정하에

ptr->x는 (*ptr).x와 동일하게 작동하게 되는것.