Creating a new Vector from Two Vectors

I'm trying to create a new vector by combining one vector to another vector. The new vector may only have elements that both vectors have.

Example:

vector_1 has: 1, 6, 9, 17, 3, 9, 4
vector_2 has: 2, 7, 19, 9, 1, 6

After creating result_vector by combining vector_1 and vector_2:

result_vector has: 9 and 6

Any help would be nice, thanks.
Good luck!
If you have any specific question, feel free to come back.
For each value in vector a, loop through vector b and if you find a match add it to vector c.
> For each value in vector a, loop through vector b and if you find a match add it to vector c.

I could do that but I've wondered if there's a function (or two) that would simplify the process. I looked at set_intersection but I've yet to get that to work.
For set_intersection to work the vectors need to be sorted before you call it.
The code in question:

sort(vector_1.begin(), vector_1.end());

sort(vector_2.begin(), vector_2.end());

set_intersection(vector_1.begin(), vector_1.end(), vector_2.begin(), vector_2.end(), result.begin());

Ok, please tell me what I'm doing wrong here?

I'm getting: exited due to signal 10 (SIGBUS).
One thing, I realize (at least I'm thinking I do) that set_intersection in examples I've seen is taking elements of arrays (not vectors) and I think storing the result into a vector, but I'm looking to create a result from two vectors, not arrays, so I'm not too certain I'm on the right track with set_intersection.
I expect your result vector isn't big enough. Did you allocate room for the results?

Well actually you don't know how big the result vector is so its best to use std::back_inserter for this:
1
2
3
4
5
sort(vector_1.begin(), vector_1.end());

sort(vector_2.begin(), vector_2.end());

set_intersection(vector_1.begin(), vector_1.end(), vector_2.begin(), vector_2.end(), back_inserter(result));


I assume the back_inserter does a push_back() on each element to be added.
> Well actually you don't know how big the result vector is so its best to use std::back_inserter for this

That worked! First time I've ever had to use back_inserter, let alone have ever heard of it, but it seems to be working nicely.

Thanks for all the help!
Topic archived. No new replies allowed.