subtract one array from another

Hi, i have two arrays a[lengthA]={2,5,7,9}, b[lengthB]={5,7}
How can i get an array a={2,9}

Here is my code, but it's not correct.

1
2
3
4
5
6
7
8
9
for (int j=0; j<lengthA;j++){
	for (int i = 0; i < lengthB; i++){

		if (a[i]==b[j]){
		a[i]=a[i+1];
		lengthA--;
		}
	}
}					
Last edited on
You could use std::remove_if:
1
2
3
void subtract_array(int* a, std::size_t& lenA, int* b, std::size_t lenB) {
    lenA = a - std::remove_if(a, a + lenA, [&](int val){ return std::count(b, b + lenB, val); });
}


However, in your case, your problem is that you are giving the wrong letters for a and b in line 4 - you are iterating over 'a' with 'j' not 'i', and the other way round for 'b'.
Last edited on
You could make a third array in the function, then copy all values of a to that array if they don't appear in b. Then return that array. I wouldn't change a at all.

EDIT: You would have to calculate the length of the third array before that though. Just count each element of a which does not appear in b.

EDIT 2: Just seeing, you don't use a function, I would though.
Last edited on
Topic archived. No new replies allowed.