Jakub Sapko
Jakub Sapko

Reputation: 316

Can you change a pointer in loop?

Let's say I have a vector of integers:

vector<int> v(n);

Which I fill up in a for loop with valid values. What I want to do is to find a index of a given value in this vector. For example if I have a vector of 1, 2, 3, 4 and a value of 2, i'd get a index = 1. The algorithm would assume that the vector is sorted in ascending order, it would check a middle number and then depending of it's value (if its bigger or smaller than the one we're asking for) it would check one of halves of the vector. I was asked to do this recursive and using pointer. So I wrote a void function like:

void findGiven(vector<int> &v){
    int i = 0;
    int *wsk = &v[i];
}

and I can easily access 0th element of the vector. However I seem to have some basic knowledge lacks, because I can't really put this in a for loop to print all the values. I wanted to do something like this:

for (int j = 0; j<v.size(); j++){
   cout << *wsk[j];
}

Is there a way of doing such a thing? Also I know it's recurisve, I'm just trying to figure out how to use pointers properly and how to prepare the algorithm so that later I can build it recursively. Thanks in advance!

Upvotes: 0

Views: 386

Answers (1)

NadavS
NadavS

Reputation: 777

The correct way is:

for (int wsk : v) {
    cout << wsk;
}

If you insist on pointers:

int* first = v.data();
for (size_t j = 0; j < v.size(); ++j) {
  cout << first[j];
}

Upvotes: 3

Related Questions