c# - 使用接口(interface)在 C++ 中使用通用容器的最佳方法是什么(即等同于在 C# 中将 IEnumerable 作为参数)

标签 c# c++ stl ienumerable

我希望 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/

相关文章:

c++ - 在类构造函数中设置 std::vector

c++ - 从列表中删除 boost::shared_ptr 的正确方法是什么?

c# - 通过提供代理 token 处理来自 webapi 的长承载 token

c# - 有人可以向我解释这段代码吗?

c# - 循环浏览菜单条中的子项

c++ - 打印出存储在 vector 中的字符串

c++ - operator< std::set 的重载

c# - Silverlight Bing 通过 SSL 映射

c++ - LLVM-IR 数组指针赋值

c++ - 是否可以使用 JNI 在 C 或 C++ 中实现 Java 接口(interface)?