Can we send part of vector as a function argument?

2019-01-18 11:56发布

问题:

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?

回答1:

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.



回答2:

Generically you could send iterators.

static const int n[] = {1,2,3,4,5};
vector <int> vec;
copy (n, n + (sizeof (n) / sizeof (n[0])), back_inserter (vec));

vector <int>::iterator itStart = vec.begin();
++itStart; // points to `2`
vector <int>::iterator itEnd = itStart;
advance (itEnd,2); // points to 4

func (itStart, itEnd);

This will work with more than just vectors. However, since a vector has guaranteed contigious storage, so long as the vector doesn't reallocate you can send the addresses of elements:

func (&vec[1], &vec[3]);


回答3:

std::vector<char> b(100); 
send(z,&b[0],b.size(),0);

Try out this.

Read this too.



回答4:

As some others already stated you can use iterators for that. You'll have to pass the start of the sequence and the end of the sequence to your worker function.

If you need more flexibility, you should take a look at slice. With slice you can for example retrieve every n-th entry of the vector.



回答5:

I was also stuck to same problem.I found one really nice trick.Suppose you want to find the minimum in range L to R (both inclusive) of arr then you can do something like this:

vector<int>arr = {4,5,1,3,7};

int minVal = *min_element(begin(arr)+L,begin(arr)+(R+1));

Means you pass the complete array and range and then you can apply the above trick.



标签: c++ vector