我仍在努力重载可以处理 vector/列表或 map 的 Sum 函数。我的 sum 函数的 vector/列表版本工作正常,我认为我的 map 版本的代码相当不错,但是当我测试它时,编译器似乎认为我正在尝试调用该函数的列表/vector 版本,并抛出一些编译器错误。相关代码如下:
template <typename T>
const double Sum(typename T start_iter, typename T end_iter)
{// code...
}
template <typename T>
const double Sum(map<typename T, double> start_iter, map<typename T, double> end_iter)
{// different code...
}
int main()
{
map<string, double> test_map; // construct empty map
test_map["Line1"] = 10; // add some data
test_map["Line2"] = 15;
Sum(test_map.begin(),test_map.end()) // this tries to call the list/vector version of sum
}
我怎么混淆了这些功能?谢谢!
最佳答案
评论中正在讨论的内容的轻微替代:
template <typename Vt>
struct getter
{
Vt operator()(const Vt& v)
{
return v;
}
};
template <typename F, typename G>
struct getter<std::pair<F, G> >
{
G operator()(const std::pair<F, G>& v)
{
return v.second;
}
};
template <typename Iterator>
int sum(Iterator it, Iterator end)
{
int r = 0;
for(; it != end; ++it)
r += getter<typename Iterator::value_type>()(*it);
return r;
}
现在 sum
函数不关心它迭代的是什么,只需依靠适当的 getter
来获取值...
例如:
std::map<int, int> f;
f[1] = 3;
f[2] = 6;
f[3] = 12;
f[4] = 24;
std::vector<int> g;
g.push_back(4);
g.push_back(8);
g.push_back(16);
g.push_back(32);
std::cout << sum(f.begin(), f.end()) << std::endl;
std::cout << sum(g.begin(), g.end()) << std::endl;
关于c++ - 重载求和函数,将列表/vector 与 map 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670008/