如何将向量的一部分作为函数参数传递? [英] How can I pass a part of a vector as a function argument?
问题描述
我在C ++程序中使用 vector
,我需要将该 vector
的一部分传递给函数.
I'm using a vector
in a C++ program and I need to pass a part of that vector
to a function.
如果是C,则需要执行以下操作(使用数组):
If it was C, I would need to do the following (with arrays):
int arr[5] = {1, 2, 3, 4, 5};
func(arr+2); // Pass the part of the array {3, 4, 5}
除了最后一部分创建新的 vector
之外,还有其他方法吗?
Is there any other way than creating a new vector
with the last part?
推荐答案
一种常见的方法是传递迭代器范围.这将适用于所有类型的范围,包括那些属于标准库容器和纯数组的范围:
A common approach is to pass iterator ranges. This will work with all types of ranges, including those belonging to standard library containers and plain arrays:
template <typename Iterator>
void func(Iterator start, Iterator end)
{
for (Iterator it = start; it !=end; ++it)
{
// do something
}
}
然后
std::vector<int> v = ...;
func(v.begin()+2, v.end());
int arr[5] = {1, 2, 3, 4, 5};
func(arr+2, arr+5);
注意:尽管该函数适用于所有范围,但并非所有迭代器类型都支持通过 v.begin()+ 2中使用的
.有关替代方法,请查看 operator +
进行增量 std :: advance
和 std :: next
.
Note: Although the function works for all kinds of ranges, not all iterator types support the increment via operator+
used in v.begin()+2
. For alternatives, have a look at std::advance
and std::next
.
这篇关于如何将向量的一部分作为函数参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!