Blu*_*rin 2 c# c++ ienumerable stl
我希望C++构造函数/方法能够将任何容器作为参数.在C#中,使用IEnumerable会很容易,在C++/STL中是否有等价物?
安东尼
C++的方法是使用迭代器.就像所有作为前两个参数的<algorithm>函数(it begin, it end, )一样.
template <class IT>
T foo(IT first, IT last)
{
    return std::accumulate(first, last, T());
}
如果您真的想将容器本身传递给函数,则必须使用"模板模板"参数.这是因为C++标准库容器不仅使用所包含类型的类型进行模板化,而且还使用分配器类型进行模板化,该类型具有默认值,因此是隐式的且未知.
#include <vector>
#include <list>
#include <numeric>
#include <iostream>
template <class T, class A, template <class T, class A> class CONT>
T foo(CONT<T, A> &cont)
{
    return std::accumulate(cont.begin(), cont.end(), T());
}
int main()
{
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    std::list<int> l;
    l.push_back(1);
    l.push_back(2);
    l.push_back(3);
    std::cout << foo(v) << " " << foo(l) << "\n";
    return 0;
}