如何编写一个可以接受数组或向量的函数? [英] How to write a function that can take in an array or a vector?
问题描述
我想编写一个带有一个参数的 C++ 函数,以便可以传入以下任一类型:
I would like to write a C++ function with one argument such that one can pass in either any of the following types:
std::vector<int>
std::array<int>
int array[numElements]
int *ptr = new int[numElements]
etc
模板是实现这一目标的最佳方式吗?
Would templating be the best way to accomplish this?
推荐答案
如果你希望能够做到 func(v)
你不能,因为我想不出你的函数可以推导出动态分配的int[numElements]
的大小.
If you expect to just be able to do func(v)
you cannot, because there's no way I can think of that your function could deduce the size of the dynamically allocated int[numElements]
.
包装它的一个好方法是采用一对前向迭代器,也就是说,如果您只需要一个一个地迭代项目,因为随机访问在某些容器上非常糟糕,例如 std::list代码>.
A good way you could wrap this is to take a pair of forward iterators, that is, if you only need iterating over items one by one, since random access is very bad on some containers like std::list
.
template<class FWIt>
void func(FWIt a, const FWIt b)
{
while (a != b)
{
std::cout << "Value: " << *a << '\n';
++a;
}
}
template<class T>
void func(const T& container)
{
using std::begin;
using std::end;
func(begin(container), end(container));
}
这将适用于以下内容:
int array[5] = {1, 2, 3, 4, 5};
func(array);
int* dynarray = new int[5]{1, 2, 3, 4, 5};
func(dynarray, dynarray + 5);
std::vector<int> vec{1, 2, 3, 4, 5};
func(vec);
func(vec.begin(), vec.end());
std::list<int> list{1, 2, 3, 4, 5};
func(list);
由于@DanielH 的更改,这也可以通过直接传递原始数组而不是作为两个指针传递(但仍然不适用于动态分配的数组).
This also works by passing raw arrays directly rather than as two pointers thanks to @DanielH's change (but still won't work with dynamically allocated arrays).
这篇关于如何编写一个可以接受数组或向量的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!