Printing a part of a vector

The exercise says:
Given a sorted array of elements and two elements a and b, with a<=b, print an array with all the elements between a and b.
Example:
INPUT
[1,3,6,8,70]
a=2
b=8
OUTPUT
[3,6]

I did the code but I think there's a problem with the element b:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

using namespace std;

int main () {
	//Initialization:
	const int N = 5;
	int vec1[N] = {1, 3, 6, 8, 70};
	int a = 2, b = 8;
	int vec2[N];
	int pos1 = 0, pos2 = 0;
	
	//Procedure:
	for (int i = 0; i<N; i++) {				//Finding position of a.
		if(a < vec1[i]) {
			pos1 = i;
			break;
		}
	}
	for (int i = 0; i<N; i++) {				//Finding position of b.
		if(b < vec1[i]) {
			pos2 = i;
			break;
		}
	}
	
	int temp = pos1;
	for (int i = 0; temp<=pos2; i++, temp++) {
		vec2[i] = vec1[temp];
	}
	
	//Output:
	//cout<<pos1<<"\n"<<pos2<<"\n";
	cout<<"[";
	for (int i = 0; i<pos2; i++) {
		cout<<vec2[i]<<" ";
	}
	cout<<"]";
	
	//Termination:
	return 0;
}


It takes all the elements from a to the last one and I don't know why. The code seems okay to me. What did I do wrong?
How many elements do you copy on loop 28-30 and how many do you print on loop 35-37?
Oh! I got the problem. Should I fix it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	int temp = pos1;
	int occ = 0;
	for (int i = 0; temp<pos2; i++) {
		vec2[i] = vec1[temp];
		occ++, temp++;
	}
	
	//Output:
	//cout<<pos1<<"\n"<<pos2<<"\n";
	cout<<"[";
	for (int i = 0; i<occ; i++) {
		cout<<vec2[i]<<" ";
	}
	cout<<"]";

Though now it stops at 8 and not at 6 like in the example.
Tip:
1
2
3
4
5
int temp = pos1;
int occ = 0;
for ( ; temp < pos2; ++occ, ++temp ) {
	vec2[occ] = vec1[temp];
}


Your new(ly revealed) problem is in the condition that determines the pos2. If you don't want to include value(s) that are equal to b, then ...

Put other way: you want only values that are less than b. Pos2 (a "one past end") should thus be not less than. That is same as greater or equal.


Another tip. You have already found pos1. Should you look for pos2 from the [0..pos1[ range? Or start the search from pos1?
Last edited on
Your new(ly revealed) problem is in the condition that determines the pos2. If you don't want to include value(s) that are equal to b, then ...

Put other way: you want only values that are less than b. Pos2 (a "one past end") should thus be not less than. That is same as greater or equal.

I'm sorry, I didn't understand that. You're saying I should write it like this:
1
2
3
4
5
6
for (int i = pos1; i<N; i++) {				//Finding position of b.
		if(b >= vec1[i]) {
			pos2 = i;
			break;
		}
	}


Because if I do like that it gives me both at the same position and then it doesn't give me any number.
if ( b <= vec1[i] )
Oh! I'm so stupid... I didn't see that typo... Thanks a lot!
Topic archived. No new replies allowed.