1

How would i go about subtracting elements from 2 arrays?

I have my array_1[5] array with elements {1, 2, 3, 4, 5} and array_2[3] with elements {2, 3, 5}. In math class i was thought that i only need to subtract the groups to be left with {1, 4}. I have tried subtracting the arrays like integers but i can't figure out how to properly use the index. I have also tried sorting and the second array and then checking if their indexes are equal but that doesn't work.

How can i get this done in C++ ?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • Possible duplicate of [What's the most efficient way to erase duplicates and sort a vector?](https://stackoverflow.com/questions/1041620/whats-the-most-efficient-way-to-erase-duplicates-and-sort-a-vector) – rustyx Jun 08 '18 at 07:06
  • You can't "remove" anything from an array. You need to use a vector. – rustyx Jun 08 '18 at 07:06
  • 4
    http://en.cppreference.com/w/cpp/algorithm/set_difference – acraig5075 Jun 08 '18 at 07:07
  • 1
    Please don't make more work for others by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under a [CC BY-SA license](//creativecommons.org/licenses/by-sa/4.0), for SE to distribute the content (i.e. regardless of your future choices). By SE policy, the non-vandalized version is distributed. Thus, any vandalism will be reverted. Please see: [How does deleting work? …](//meta.stackexchange.com/q/5221). If permitted to delete, there's a "delete" button below the post, on the left, but it's only in browsers, not the mobile app. – Makyen May 10 '20 at 18:44

1 Answers1

6

You're looking for the difference between two sets which is one of the standard algorithms

#include <algorithm>
#include <vector>
#include <iterator>

int array_1[] = { 1, 2, 3, 4, 5 };
int array_2[] = { 2, 3, 5 };

std::vector<int> difference;

std::set_difference(std::begin(array_1), std::end(array_1), std::begin(array_2), std::end(array_2), std::back_inserter(difference));

// difference now contains { 1, 4 }

Based on your comments, I suggest you have your arrays as std::vectors. Then it becomes simpler.

std::vector<int> array_1 = { 1, 2, 3, 4, 5 };
std::vector<int> array_2 = { 2, 3, 5 };

std::set_difference(array_1.begin(), array_1.end(), array_2.begin(), array_2.end(), std::back_inserter(difference));
acraig5075
  • 10,588
  • 3
  • 31
  • 50