Computing the scalar product of two vectors in C++

后端 未结 5 983
一生所求
一生所求 2020-12-31 03:34

I am trying to write a program with a function double_product(vector a, vector b) that computes the scalar product of two vectors. T

5条回答
  •  太阳男子
    2020-12-31 04:23

    Unless you need to do this on your own (e.g., writing it is homework), you should really use the standard algorithm that's already written to do exactly what you want:

    #include 
    #include 
    #include 
    
    int main() {
        std::vector a {1, 2, 3};
        std::vector b {4, 5, 6};
    
        std::cout << "The scalar product is: "
                  << std::inner_product(std::begin(a), std::end(a), std::begin(b), 0.0);
        return 0;
    }
    

    Note that while begin(a) and end(a) are new in C++11, std::inner_product has been available since C++98. If you are using C++ 98 (or 03), it's pretty easy to write your own equivalent of begin and end to work with arrays though:

    template 
    T *begin(T (&array)[N]) {
        return array;
    }
    
    template 
    T *end(T (&array)[N]) {
        return array + N;
    }
    

    Using these, a C++ 98 version of the previous code could look something like this:

    int main() {
        double a[] = {1, 2, 3};
        double b[] = {4, 5, 6};
    
        std::cout << "The scalar product is: "
                  << std::inner_product(begin(a), end(a), begin(b), 0.0);
        return 0;
    }
    

    Note that the begin and end above will only work for arrays, where the begin and end in C++11 (and later) will also work for normal collection types that define a .begin() and .end() (though it's trivial to add overloads to handle those as well, of course):

    template 
    typename Coll::iterator begin(Coll const& c) { return c.begin(); }
    
    template 
    typename Coll::iterator end(Coll const& c) { return c.end(); }
    

提交回复
热议问题