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

Implementing '+' operator for std::vector

本文关键字:运算符 std vector 实现      更新时间:2023-10-16

我正在尝试添加对 std::vector 的支持。这是我到目前为止的代码。不起作用的部分是我尝试打印结果的部分。我知道 valarray,但我无法让它按照我想要的方式工作(主要是我没有找到一种将向量转换为 valarray 的简单方法(。

这是错误:

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

编译器错误会准确地告诉您该怎么做。但是,与其滚动自己的for循环,我建议使用 std::copy()

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的意外副作用。

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

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

std::vector<T>::iterator it之前添加类型名。应该是typename std::vector<T>::iterator
您可以参考此SO链接以获取有关类型名称的详细信息 我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?

相关文章: