1

I'm trying to add support for addition for std::vector. Here's the code I have so far.. The part that doesn't work is the part where I attempt to print the result. I am aware of valarray but I can't get it to work the way that I want (mostly I haven't found an easy way to convert vectors into valarrays).

This is the error:

../src/VectorOperations.cpp:26:6: error: need 'typename' before 'std::vector<T>::iterator' because 'std::vector<T>' is a dependent scope

class VectorOperations
{
public:
    //Vector Operations
    std::vector<double> logv(std::vector<double> first);
    std::vector<double> raiseTo(std::vector<double> first, int power);
    std::vector<double> xthRoot(std::vector<double> first, int xth);
    double sumv(std::vector<int> first);

    std::vector<double> operator + ( const std::vector<double> & ) const;
    std::vector<double> operator - ( const std::vector<double> & ) const;
    std::vector<double> operator * ( const std::vector<double> & ) const;
    std::vector<double> operator / ( const std::vector<double> & ) const;

};


template <typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)
{
    assert(a.size() == b.size());
    std::vector<T> result;
    result.reserve(a.size());
    std::transform(a.begin(), a.end(), b.begin(),
               std::back_inserter(result), std::plus<T>());

    std::cout<<"Results from addition follow: \n";
    //HERE'S THE PROBLEM: I WANT TO PRINT OUT BUT I GET ERRORS
        for(std::vector<T>::iterator it = a.begin(); it != a.end(); ++it) {
            /* std::cout << *it; ... */
        }
    return result;
}
frickskit
  • 614
  • 1
  • 8
  • 18

3 Answers3

1

std::vector<T>::iterator depends on template type, try to add typename:

for(typename std::vector<T>::iterator it = a.begin(); it != a.end(); ++it) {
    ^^^^^
billz
  • 41,716
  • 7
  • 75
  • 95
1

The compiler error tells you exactly what to do. However, rather than roll your own for-loop, I recommend using std::copy():

std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ", "));

For example:

template <typename T>
std::ostream& operator <<(std::ostream& os, std::vector<T> const& v)
{
    os << "{";
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ", "));
    return os << "}";
}

[Apply your own formatting style to taste.]

Then you can call:

std::cout << "Results from addition follow: \n" << result << std::endl;

[Preferably from outside operator +, as this would be an unexpected side-effect of adding two vectors.]

Johnsyweb
  • 121,480
  • 23
  • 172
  • 229
0

add typename before std::vector<T>::iterator it. It should be typename std::vector<T>::iterator
You can refer to this SO link for detal information about typename Where and why do I have to put the "template" and "typename" keywords?

Community
  • 1
  • 1
user258367
  • 2,917
  • 2
  • 16
  • 17