I think I’m lacking some basic understanding of assignment in C/C++ here! I have a function that computes the set union between two string vectors. The reason I do this is because the algorithm library’s function set_union requires that both vectors are sorted first and if I do it the following way then I can’t forget to sort:
vector<string> SetOperations::my_set_union(vector<string> set1,
vector<string> set2) {
sort(set1.begin(), set1.end());
sort(set2.begin(), set2.end());
vector<string> v;
set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), back_inserter(v));
return v;
}
I then do the following:
vector<string> vec = set_ops.my_set_union(vec1, vec2);
where vec1 and vec2 are string vectors containing a single "a" and "a" each and set_ops is an instantiation of a class that I have these set operations in (like the one above). They both definitely have these elements – I have printed the two vectors out.
For some (simple?) reason, vec ends up having a single element of "a" instead of two elements ("a" and "a").
Any ideas what I’m doing wrong? Am I meant to a copy function or something?
Thank you :).
You have to use
mergeinstead ofset_union.set_unionwill eliminate similar enteries.see merge and set_union refrences.