我希望 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;
}
关于c# - 使用接口(interface)在 C++ 中使用通用容器的最佳方法是什么(即等同于在 C# 中将 IEnumerable 作为参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1920910/