为std :: vector实现'+'运算符

时间:2013-02-17 04:24:32

标签: c++ overloading

我正在尝试为std :: vector添加对添加的支持。这是我到目前为止的代码..不起作用的部分是我尝试打印结果的部分。我知道valarray,但我不能按照我想要的方式工作(大多数时候我没有找到一种简单的方法将矢量转换为valarrays)。

这是错误:

../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;
}

3 个答案:

答案 0 :(得分:1)

std::vector<T>::iterator取决于模板类型,请尝试添加typename

for(typename std::vector<T>::iterator it = a.begin(); it != a.end(); ++it) {
    ^^^^^

答案 1 :(得分:1)

编译器错误告诉您 完全 该怎么做。但是,我推荐使用std::copy()

,而不是推出自己的for循环
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ", "));

例如:

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 << "}";
}

[应用您自己的格式样式。]

然后你可以打电话:

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

[最好来自 外部 operator +,因为这会增加两个vector s的意外副作用。]

答案 2 :(得分:0)

std::vector<T>::iterator it之前添加typename。它应该是typename std::vector<T>::iterator
您可以参考此SO链接获取有关typename Where and why do I have to put the "template" and "typename" keywords?

的详细信息