Shravan40 Shravan40 - 4 years ago 193
C++ Question

How to find union of n vector?

I have a 2-D vector of hyperedges as well as an adjacency list. I have to find the union of

hyperEdges[i].size()
vectors, but I can only find the union of just two vectors. What improvement can I make to my code below to do this?
I want to store the union into newly declared 2-D vector
connectedEdges


void find_union()
{
connectedEdges.resize(nEdges+1);
for(int i = 1; i <= nEdges; i++)
{
vector<int>::iterator it;
connectedEdges[i].resize(nEdges+1);

for(int j = 1; j < hyperEdges[i].size()-1; j++)
{
int p = hyperEdges[i][j-1];
int q= hyperEdges[i][j];
it = set_union(adjL[p].begin(), adjL[p].end(),adjL[q].begin(),adjL[q].end(), connectedEdges[i].begin());
connectedEdges[i].resize(it-connectedEdges[i].begin());
}
}
}


Example :
{1,2,4,6,8}


{1,2,3,5,6}


{1,4,7,13,15}


Union of these three sets should be
{1,2,3,4,5,6,7,8,13,15}

But my program returns
{1,2,3,4,5,6,8}

Answer Source

If you have a lot of vectors, I'd suggest to insert content of all of them into single std::set and then dump it back into std::vector.

Something like that:

std::vector<std::vector<int>> src = ...;
std::set<int> all;

for(int i = 0; i < src.size(); i++) {
    all.insert(src[i].begin(), src[i].end());
}

std::vector<int> result(all.begin(), all.end());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download