Using Iterators to find the union of two vectors

So this code is suppposed to find the vector between two vectors that a user inputs. The program builds just fine, but when I run the program, it gets stuck on the function that is supposed to generate the union of the two vectors (marked in the code).

What is being done wrong in this instance?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> vec_union(vector<int> &vect1, vector<int> &vect2);

int main()
{
    vector <int> vect1, vect2, unionVect;

    cout << "Enter a list of numbers for vect1. When finished enter 999.\n";
    int next;
    cin >> next;

    while (next != 999)
    {
        vect1.push_back(next);
        cout << next << " added.\nNext value: ";
        cin >> next;
    }

    cout << "Enter a list of numbers for vect2. When finished enter 999.\n";
    cin >> next;

    while (next != 999)
    {
        vect2.push_back(next);
        cout << next << " added.\nNext value: ";
        cin >> next;
    }

    unionVect = vec_union(vect1, vect2); //PROGRAM GETS STUCK HERE

    cout << "Union of vect1 and vect2: ";
    for(unsigned i = 0; i < unionVect.size(); i++)
    {
        cout << unionVect[i] << " ";
    }
    cout << endl;

    return 0;
}

vector<int> vec_union(vector<int> &vect1, vector<int> &vect2)
{
    vector<int> unionVect;

    vector<int>::iterator iter1 = vect1.begin();
    vector<int>::iterator iter2 = vect2.begin();

    while(iter1 != vect1.end())
    {
        while(iter2 != vect2.end())
        {
            if(*iter1 == *iter2)
            {
                unionVect.push_back(*iter1);
            }
        }
    }

    return unionVect;
}
You never advance your iterators.

Add after line 60:
iter2++;

Add after line 61:
iter1++;
Do you mean union as in set unions (math concept) or just "values which are equal and on same place".

In other words, what is the union of {1, 2, 3} and {3, 2, 1}?
Topic archived. No new replies allowed.