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

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

void find_union()
for(int i = 1; i <= nEdges; i++)
vector<int>::iterator it;

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());

Example :



Union of these three sets should be

But my program returns

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