user1364012
user1364012

Reputation: 35

Overloading operators for STL Vector

I know that it is usually not the best idea, but i decided to give it a try. I'm trying to overload + operator to make element wise addition of two vectors. For some reason it correctly returns only the first value in the vector. I cant figure out what is going wrong ? It also wont work if i'll use push_back instead resizing when calculating elements of sum array. Here is the code :

    #include "stdafx.h"
    #include <iostream>
    #include "conio.h"
    #include <vector>

    using namespace std;

    class dvector{

    public:
        vector<double> q;
        dvector(vector<double>);
        dvector();
    };
    dvector::dvector(vector<double> a) {
        q=a;
    };
    dvector::dvector() {
        vector<double> q;
    };

    dvector operator+(dvector c1, dvector c2)
    {
        int sz=c1.q.size();
        dvector sum;
        sum.q.resize(sz);
        double temp;
        for (int i=0; i<sz; i++){
            sum.q[i]=c1.q[i]+c2.q[i];
            return sum;
        }
    }


    int _tmain(int argc, _TCHAR* argv[])

    {
        vector<double> test1;
        test1.resize(10);
        for (int i=0; i<10;i++){
            test1[i]=i;
        }
        vector<double> test2;
        test2.resize(10);
        for (int i=0; i<10;i++){
            test2[i]=2;
        }
        dvector dtest1(test1); 
        dvector dtest2(test2); 
        dvector sum=dtest1+dtest2;

        for (int i =0;i<10;i++)

            {
                cout<<sum.q[i]<<' ';
            }
        getch();
        return 0;
    }

Upvotes: 1

Views: 233

Answers (2)

billz
billz

Reputation: 45410

Because you return out too quickly. return statement will not only break out of for loop but also return out of function.

dvector operator+(dvector c1, dvector c2)
{
    int sz=c1.q.size();
    dvector sum;
    sum.q.resize(sz);
    double temp;
    for (int i=0; i<sz; i++){
        sum.q[i]=c1.q[i]+c2.q[i];
        //return sum;  // don't return until you finish calculating
    }
    return sum;    // move to here
}

Upvotes: 4

Zeta
Zeta

Reputation: 105876

You return in your for-loop right after the first iteration. You should move return sum; to the last line of operator+.

Upvotes: 5

Related Questions