对于我的 C++ 类(尚未涵盖 Boost)的练习,我无法编写模板化方法来接受两个迭代器来对 STL 容器中的数值求和。
考虑以下示例:
#include <iostream>
#include <iterator>
#include <vector>
template<typename T>
double Sum(const T & c) {
return 42.0; // implementation stubbed
}
// need help writing this method signature to accept two iterators
template<typename T>
double Sum(const typename T::const_iterator & begin,
const typename T::const_iterator & end) {
return 43.0; // another implementation stub
}
int main() {
std::vector<double> v;
v.push_back(3.14);
v.push_back(2.71);
v.push_back(1.61); // sums to 7.46
std::cout << Sum(v) << ' ' // line 23
<< Sum(v.begin(), v.end()) // line 24
<< '\n';
}
我希望此代码能够输出42 43
,但无法编译。
g++ 给我的错误是:
test_exercise2.cpp: In function ‘int main()’:
test_exercise2.cpp:24: error: no matching function for call to ‘Sum(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >)’
如果我注释掉第 24 行,我会得到42
预期的输出。
无论是否存在第二个模板化方法,我都会收到相同的错误消息,因此由于某种原因,它无法将第 24 行的调用解析为我编写的第二种方法。
对于接受两个迭代器的方法,我必须有什么签名?
我之所以坚持这一点是因为我需要支持对std::map<K, V>
. 这将需要另外两个重载来调用->second
而不是取消引用迭代器:
1. template<typename K, typename V> double Sum(const std::map<K, V> & m);
(我可以接受这个)
2.另一个涉及地图上的迭代器。
std::map
如果我能弄清楚如何为std::list
and指定迭代器的传递,我觉得我将能够编写方法std::map
。我可以接受使用模板模板的解决方案。
编辑:问题的准确措辞(省略非贡献的句子)。
“上一个练习”中的容器是std::vector<double>
, std::list<double>
, std::map<std::string, double>
.
创建一个名为 Sum() 的模板函数,它接受模板参数 T 作为输入并返回一个双精度值。模板参数将是一个容器。
- 在实现中,最后得到一个迭代器(T::const_iterator)。然后创建一个循环来迭代容器 T 并添加所有值。最后返回总和。
- 在主程序中,为与上一个练习不同的容器调用 Sum() 函数。
创建的 Sum() 函数计算整个容器的总和。还要创建一个 Sum() 函数来计算两个迭代器之间的总和。然后该函数使用迭代器类型的模板参数并接受两个迭代器,即开始迭代器和结束迭代器。