I have an issue with set.union (C++)

966 views Asked by At

I'm trying to union two sets (in a vector).

setA contains a, b. setB contains a, c.

After union, result is supposed to contain a, b, c. However, the program is not working, it is having some kind of debug error.

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
vector<char> setA;
vector<char> setB;
vector<char> result;
vector<char>::iterator it;

setA.push_back('a');
setA.push_back('b');
setB.push_back('a');
setB.push_back('c');

it = set_union(setA.begin(), setA.end(), setB.begin(), setB.end(), result.begin());

for (int i = 0; i < result.size(); i++)
{
    cout << result[i] << " ";
}

system("PAUSE");
}

Does anyone know what the problem is?

1

There are 1 answers

0
Khaled Alshaya On

You should either resize the result vector to accommodate the max size of the union, or use std::back_inserter:

it = set_union(setA.begin(), setA.end(),
               setB.begin(), setB.end(),
               back_inserter(result));