Composing vector<int> of unique elements

I am trying to compose a vector of all unique elements from another vector,
I have used this method before with strings in Java, but I cannot get it to work in C++ right now.

I clear the unique vector each time since in findUnique() I push it back and I want it to start pushing back at a[0] instead of just adding to the vector...

I really do not see what is wrong with this....
when I go to print out unique each time through it prints nothing because unique never has anything added to it....it is always having length 0

thanks! :)

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
#include <iostream>
#include <vector>

using namespace std;

void findUnique(vector<int> &a, vector<int> &b);

int main()
{
	int input;
	vector<int> all;
	vector<int> unique;
	
	cout<<"Enter an integer: ";
	while(cin>>input)
	{	


	  all.push_back(input);  

	  findUnique(all, unique);

	  for(int i=0;i<unique.size();i++)
	    cout<<unique[i]<<" ";
	  
	  
	  unique.clear();
	  cout<<"Enter an integer: ";
	}
	
}

void findUnique(vector<int> &a, vector<int> &b)
{
	for(int i=0;i<a.size();i++)
	{
	  bool existsInB = false;
	  for(int j=0;j<b.size();j++)
	  {
	    if(a[i] == b[j])
	    {
	      existsInB = true;
	      break;
	    }
	    if(!existsInB)
	    {
	     b.push_back(a[i]);
	    }
	  }
	}
}

Last edited on
If b is empty (which it starts out to be), then the for() loop on line 38 never executes, which means the push_back() on 47 never executes. (There is an algorithmic problem here which you can figure out).

In find unique, there is one problem with an incorrectly placed closing bracket }. You have made it this far, I am sure you will find it if you look really hard.

EDIT: pf, you spoiled it j.
Last edited on
Hey thanks guys ! :)

......that was a really bad error putting the if statement inside the for loop.....

I should punch my self in the face lol


Works perfectly now :)

Now I just gotta do the final step of the project.....which is really easy O.o


:)
Topic archived. No new replies allowed.