Search code examples
c++vectorpass-by-reference

Is it possible to send part of vector as a vector to a function?


I want to see if it is possible to pass part of vector to a function so that it appears as a normal vector to the function. More importantly, I want this to be done in O(1), constant time. I don't want to iterate the vector to make a new one. In fact, I also want the size of the new vector to change to 40 in the following example.

void func(vector <int> &v){

    //calling index 10  to 50 of v
    func(v[10..50])
}

Solution

  • Use iterators as the parameters to the range-based function, and pass in the required range. Your code in the function become

    funcWithRange(v.cbegin()+10, v.cbegin()+50);
    

    with function signature

    void funcWithRange(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last)
    

    This could be generalized by making this a function template with the vector member type as its template parameter, or still further to any container supporting this type of range iteration. As noted in the comments, <algorithm> has many examples of this pattern.

    std::distance(first, last); will return the desired altered size. I don't think you can get closer to meeting your requirements without making a physical copy.