How to pass a vector from an intermediate index to a function and use it with zero based indexing in that function.

Hi guys :),

In case of arrays, we can pass them from an intermediate index to a function and use zero based indexing in the passed function.

eg :

1
2
3
4
5
6
7
8
9
10
11
12
void f(int a[])
{
cout << a[0]; // In this function a[0] actually refers to 3rd element of the 
              // original array a.
}

int main()
{
int a[10] = {0};
f(a+2);            // This array will be available as zero based indexing 
return 0;        // from 3rd element in function f.
}


Do we have some similar mechanism for vectors ?

something like :

1
2
3
4
5
6
7
8
9
10
11
void f(vector<int> &a) //I am aware that this will give error. Kindly let me 
{                      // know the right way.
cout << a[0] << endl; // Should refer to 2nd element of original vector.
}

int main()
{
vector<int> a(100,0);
f(a+2);    // I understand that this gives error.Kindly let me know the right 
return 0;  // way
}


Thanks all :)
Last edited on
The short answer is no. The long answer is nooooooooooo. It's pointless, anyway. Just pass the vector and an index representing the required base. Then offset from that.

Your question shows a total lack of understanding about what a vector is. Have you done the beginner exercise of creating your own vector class? That would show you why this is a silly question.
work with iterators
1
2
3
4
5
6
void f(vector<int>::iterator a){
   std::cout << *a << ' ' << a[0] << ' ' << *(a-1) << '\n';
}

vector<int> a(100, 0);
f(a.begin()+2);
note that then you lose the .size() property, so you may want to pass a two iterators, begin, end, that delimits the working range [)
Topic archived. No new replies allowed.