C++ need help with recursion question

Hi im doing an exercise which requires recursion to change the values of vector to 3*x. I have two functions, one changes the values and another returns the vector. I'm stuck on the recursion bit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  int f (int x);
vector<int> v1 (vector <int> p1);
int main () {
	vector<int> x1= {20,30,90};
	v1(x1);
	for (int i=0;i<3;i++) {
		cout << x1.at(i) << " ";
	}
}

int f (int x) {
	return 3*x;
}
vector <int> v1(vector <int> p1) {
	if (p1.size()==0) {
		return p1.clear();
	}
	else {
		return v1(p1.begin(),p1.end()-1) + f(p1.at(p1.size())); 
	}
}

I'm trying to shorten the vector and change its values to 3*x. My recursion line is probably wrong but I can't figure out the solution.
I am confused. Are you trying to scale the values in a vector by some number x? If so, recursion isn't needed.

return p1.clear(); will never work. It's not returning a type at all.

return v1(p1.begin(),p1.end()-1) + f(p1.at(p1.size())); is not going to work either. I'm not sure what you're trying to do here, but you're passing iterators into the function v1 instead of an actual vector.
Hey sorry for the late reply. The exercise requires you to use recursion.
What im trying to do is shortening the vector by taking off the end index and multiplying that index by 3. So for example if vector is {1,2,3,4}
1 , 2, 3, 4 (4*3)
1, 2,3 (3*3)
1,2 (2*3)
1 (1*3)
So once the program resumes, it scales the values by 3.

return v1(p1.begin(),p1.end()-1) + f(p1.at(p1.size())); The second part is the scaling factor while the 1st bit tries to reduce the array.

My base case would be when vector.size() is 0, hence returning the empty array.
Last edited on
Recursion exercises like this are common, so no surprise.

The trick is to think of a vector (or list or array or whatever) as a single item followed by the rest of the vector. The rest of the vector can be thought of in the exact same way, u till there is nothing left.

So, given a vector of the three values {1, 2, 3}, we can take it as the value 1 and the rest being {2, 3}. Modify 1 with f(), and append it to your output vector. Next, repeat with the rest: {2, 3}.

The only task is to know when to stop. In the case of a vector, that's easy: stop when there is nothing in the vector. That is, if you are given an empty vector, do not spend anything to the result vector and do not recursively call the function.

Hint: you CAN use iterators to index what part of the input vector is considered "the rest".

Vector<int> v1( vector <int> ::iterator first, vector <int> ::iterator last )
{
// first is the element to transform
// first+1 to last is the resr
// if first == last, then the input vector is empty
}

Hope this helps
Topic archived. No new replies allowed.