我们可以作为函数参数发送矢量的一部分吗? [英] Can we send part of vector as a function argument?

查看:82
本文介绍了我们可以作为函数参数发送矢量的一部分吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++程序中使用向量(我是初学者)。

我需要发送 vector 到函数。



如果是 c ,我需要这样做(使用数组):

  int arr [5] = {1,2,3,4,5}; 
func(arr + 2); //发送零件数组{3,4,5}

向量与最后一部分?

解决方案

一种常见的方法是传递迭代器范围。这将适用于所有类型的范围,包括属于标准库容器和平面数组的范围:

  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 中使用的运算符+ 有关替代方法,请查看 std :: advance std :: next 。 / p>

I'm using vector in a c++ program (and I'm a beginner).
And I need to send a part of vector to a function.

If it was c I need to do this (with arrays):

int arr[5] = {1, 2, 3, 4, 5};
func(arr+2);    //to send part array {3, 4, 5}

Is there a way other than creating a new vector with 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
  } 
}

then

std::vector<int> v = ...;
func(v.begin()+2, v.end());

int arr[5] = {1, 2, 3, 4, 5};
func(arr+2, arr+5);

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天全站免登陆