1

Could anyone tell me the simplest way to check if a vector A, includes an element of vector B?

it would be sort of:

   for every element in A (
   if (none of the elements in B exist in A) do something and B changes
   else (do nothing) )

I guess it could be done by with some loops. But is there a function that would make it easier?

remi
  • 937
  • 3
  • 18
  • 45
  • 5
    Are the elements in A and B sorted? If not, would sorting them be allowed? – Jerry Coffin Mar 19 '15 at 08:11
  • This might be helpful: http://stackoverflow.com/questions/17394149/how-to-efficiently-compare-vectors-with-c/17394298#17394298 – stefan Mar 19 '15 at 08:13
  • I don't fully understand the logic of the program: the loop `for every element in A` loops over the `size` of `A` rather than the elements, as you don't seem to use the current element in the loop body (`if none of the elements in B exist in A` is independent of a specific element in A). Can you please clarify? – stefan Mar 19 '15 at 08:17
  • Thanks guys. Actually I just found a completely different approach to my problem. So I might close this post. Sometimes just writing down my question, helps me think! – remi Mar 19 '15 at 08:17
  • What if there are two equal elements in the same vector should they be treated as a single object? – W.F. Mar 19 '15 at 08:17
  • @remi000: Don't hesitate to post your solution as answer as well as it may help others. – Jarod42 Mar 19 '15 at 17:34

2 Answers2

2

The STL includes function is designed for exactly this.

http://www.cplusplus.com/reference/algorithm/includes/

APD
  • 1,459
  • 1
  • 13
  • 19
  • I just found a complete different approach. But this would probably be my solution if not! Thank you! – remi Mar 19 '15 at 08:19
0

You std::sort them, then use std::set_intersection (or similar algorithm) to have included elements.

Jarod42
  • 203,559
  • 14
  • 181
  • 302