PerritoPerron said:
Hi there fellas..
I am learning this powerful language, but came accross a concatenation
problem that I can't resolve.
I have 2 arrays
A1[] = {1,2,3,4};
A2[] = {1,3,5,7};
I need to put them together in an int array that looks like this.
A3[32] = {1,2,3,4,5,7};
Sum them both, but skip duplicates..
Can some1 Help Please...
Thanks...
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> vec1(4), vec2(4), vec3;
vec1[0] = 1;
vec1[1] = 2;
vec1[2] = 3;
vec1[3] = 4;
vec2[0] = 1;
vec2[1] = 3;
vec2[2] = 5;
vec2[3] = 7;
vec3.reserve(8); // reserve space for the maximum
possible number of elements necessary
std::set_union(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(),
std::back_inserter<std::vector<int> >(vec3));
vec3.swap(std::vector<int>(vec3)); // shrink-to-fit (if desired)
std::copy(vec3.begin(), vec3.end(),
std:
stream_iterator<int>(std::cout, " "));
std::cout << '\n';
return 0;
}
There are a number of things to explain about this:
1) std::vector<int> vec1(4) creates a std::vector (a sort of self-managing
array) with current size 4.
2) vec3.reserve(8); does *not* resize the vector, it ensures that the
vector's capacity (distinct from its size) is at least 8. This means that
the memory has been allocated for at least 8 elements, even though the
current number of elements (the size of the vector) is still 0.
3) std::set_union(<blah>) is the bit which does what you want, since what
you want is in fact just a set union operation.
4) std::back_inserter<std::vector<int> >(vec3) is an output iterator which
pushes things onto the end of vec3.
5) vec3.swap(std::vector<int>(vec3)); trims excess capacity from the vector
(a so-called "shrink-to-fit" operation). Although the size of vec3 will be 6
after the set_union, the capacity will still be at least 8. Shrink-to-fit
attempts to make it as small as possible (whilst still greater than 6),
though the exact capacity afterwards depends on the implementation.
6) std::copy(<blah>) outputs the elements of the vector to std::cout, using
an ostream_iterator which separates the elements with a space (" ").
While we're using lots of stuff from the Standard Library, here's a book
recommendation:
The C++ Standard Library (Josuttis)
HTH,
Stuart.