向量加法运算符无法正常工作

时间:2016-12-03 16:21:03

标签: c++ vector operator-overloading

我创建了3个向量,其中向量3应该是向量1和向量2的值的总和。向量中的每个元素由值,位置和指向下一个元素的指针组成。 Vector 3没有正确添加值,我无法弄清楚问题是什么。任何帮助都将非常感激 - 我已附上下面的代码片段。 干杯

class element {
public:
    int value;
    int position;
    element * next;
    element() {
        next = nullptr;
    }
    element(int i, int j) {
        value = i;
        position = j;
        next = nullptr;
    }
};

class my_vector {
public:
    int size;
    int num_elements;
    element * head;
    my_vector() {
        num_elements = 0;
        head = nullptr;
    }
    my_vector operator + (my_vector v);
    void print();
    void add_element(int v, int p);
    void input();
};

void my_vector::add_element(int v, int p) {
    element * x;
    x = new element(v, p);
    x - > next = head;
    head = x;
}

void my_vector::input() {
    cout << "Enter number of elements" << endl;
    int num, v, p;
    cin >> num;
    cout << "Enter elements in value position pairs" << endl;
    for (int i = 0; i < num; i++) {
        cin >> v >> p;
        add_element(v, p);
    }
}

my_vector my_vector::operator + (my_vector v) {
    my_vector temp; // Vector 3
    element * p1 = head;
    element * p2 = v.head;

    while (p1 && p2 != nullptr) {

        if (p1 - > position == p2 - > position) {
            int ps = p1 - > position;
            int sum = p1 - > value + p2 - > value;
            temp.add_element(sum, ps);
            p1 = p1 - > next;
            p1 = p2 - > next;
        }

        if (p1 - > position != p2 - > position) {

            if (p1 - > position > p2 - > position) {
                int vs = p2 - > value;
                int pst = p2 - > position;
                temp.add_element(vs, pst);
                num_elements++;
                p2 = p2 - > next;
            }

            if (p2 - > position > p1 - > position) {
                int vs = p1 - > value;
                int pst = p1 - > position;
                temp.add_element(vs, pst);
                num_elements++;
                p1 = p1 - > next;
            }
        }
    }
    return temp;
}

int main() {
    my_vector v1, v2, v3;
    v1.input();
    v2.input();
    v3 = v1 + v2;
    return 0;
}

0 个答案:

没有答案