如何将向量的一部分作为函数参数传递? [英] How can I pass a part of a vector as a function argument?

查看:80
本文介绍了如何将向量的一部分作为函数参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆