更新时间:2023-02-23 14:00:34
一种常见的方法是传递迭代器范围.这将适用于所有类型的范围,包括那些属于标准库容器和纯数组的范围:
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
.