实现 std::vector 的'+'运算符
Implementing '+' operator for std::vector
我正在尝试添加对 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链接以获取有关类型名称的详细信息 我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?
相关文章:
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 关于 std::min, std::max 中的比较运算符的混淆
- C++:无法使用 "=" 运算符更改 std::p air 的值
- 为 std::variant 提供一个运算符 ==
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- C++矩阵类运算符使用 std::common_type_t 和复数的实现
- 错误:为"运算符 std::string {aka std::__cxx11::basic_string}"指定的返回类型<char>
- 运算符/ STD :: Chrono ::持续时间和自定义类型与Clang
- ostream 和运算符 std::basic_string<char, std::char_traits<char>, std::分配器<char>>?
- 为什么显式运算符 std::string 不起作用
- 运算符< std::set 的重载
- 运算符< std::map 的 int 类型比较的重载?(我希望它按降序排序。
- 运算符=(std::p romise&&) 在 C++11 中的结果是什么?
- 绑定运算符=std::string的成员
- 传递 const std::auto_ptr<> 作为 std::auto_ptr<_Tp>::运算符 std::auto_ptr_ref<_Tp1>() 的参数丢
- 运算符<< std::stringstream 派生类的重载(只是)
- 重载运算符 std::ostream& 运算符<<打印实例内存地址