This program does not crash but behaves badly due to not allocating enough space for vector z in line 21. If I comment out line 21 and instead uncomment line 23, things work well. If I comment out both lines 21 and 23, the program will crash, presumably because I am writing to a vector with no space allocated. For the program to work well when resizing on line 37, z has to have a size of at least 3. I assume that I am just getting lucky as well. Potentially only allocating z to be size 1 could make the program crash too. My understanding of STL is that the programmer is responsible for making sure that the size of the z vector is adequate when the program gets to line 27. No size check is done because checking sizes slows performance. My question is "Can I change the code so that sizes are checked or at least an exception is thrown that can be caught so the program does not crash? If so, how?".
Program output is as follows...
Before resizing-iterator:1: 1 2 3
Before resizing-z.end():1: 1
After resizing:3: 1 0 0
The first line gives the correct union, but proves that the set_union
function did not resize the z vector from 1 to 3. Line 2 proves that the iterator returned is BEYOND the end of the vector. Line 3 shows that the resizing threw away the 2 and the 3.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void print_int(int x)
{
cout << " " << x;
}
int main()
{
vector<int> x;
vector<int> y;
vector<int> z;
x.push_back(1);
x.push_back(2);
y.push_back(2);
y.push_back(3);
z.resize(1); // if this line is commented out, program will crash. I am
// ASSUMING that it COULD crash with a size of 1.
//z.resize(x.size() + y.size()); // probably the better way to do it
vector<int>::iterator it;
it = set_union(x.begin(), x.end(), y.begin(),
y.end(), z.begin());
cout << "Before resizing-iterator:" << z.size() << ":";
for_each(z.begin(), it, print_int);
cout << endl;
cout << "Before resizing-z.end():" << z.size() << ":";
for_each(z.begin(), z.end(), print_int);
cout << endl;
z.resize(it - z.begin());
cout << "After resizing:" << z.size() << ":";
for_each(z.begin(), z.end(), print_int);
cout << endl;
return 0;
}