创建一个将任何容器的所有元素加起来的模板函数

问题描述 投票:0回答:2

我需要实现一个模板功能,该功能将汇总容器内的所有元素。容器可以是:矢量,堆栈,地图,数组,集合,列表...

最佳方法是什么?例如,我们无法通过迭代器遍历整个堆栈,并且地图包含键值对...这是一个问题。

我认为使用std :: is_same值得,但是您需要在其中指定特定类型。

c++
2个回答
0
投票
template <typename T> class SumCont { public: T sum(vector<T> array){ T sm=0; for(auto things:array) { sm=sm+things; } return sm; } T sum(T *array){ T sm=0; int length=sizeof(array); for(int i=0; i < length; i++) { sm=sm+array[i]; } return sm; } }; int main() { vector<int> lol={2,3,4,5}; int lol2[]={3,4,5,6}; SumCont<int> p; cout << p.sum(lol) << endl; cout << p.sum(lol2); return 0; }

-2
投票
template< template<class Key, class T, class Compare = std::less<Key>, class Alloc = std::allocator<std::pair<const Key,T> > > class Container, class Key, class Value/*, class Compare, class Alloc*/> Value sum(const Container<Key, Value>& collection) { // TODO: calculate sum of all elements }
© www.soinside.com 2019 - 2024. All rights reserved.