Remove duplicates vector of strings, keep first instance. Can't use algorithm

I have a vector of

strings.vector input;

1
2
3
4
5
6
7
8
bob 
sam
bob 
sammom
aardvark    
money
aardvark    
wanted

I need to remove the duplicates but each part of the vector corresponds to the next location. They are pairs.

ex. bob corresponds to the its definition, which is sam.

I need to keep the first instance, so keep bob and sam, but remove the second instance of bob, so remove bob and sammon. Only the first instance of the pair need to kept.

It doesn't matter if the sam and sammon don't match, all that matters is the first part of the pair.

The vector is already in alphabetical order. I can't use the algorithm library.
Last edited on
Iterate through the vector; every time you see a new word, add it to a separate list of words. If you have already seen a word, remove it from your input.
Why does my code not remove the duplicates?

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
        vector<string> input;
	int size=input.size();

	//add data to screen here
	string *strarray;
	strarray = new string[input.size()];
	for(int i=0; i<input.size(); i++){
	   strarray[i] = input[i];//Copy the vector to the string
	}

	// erase duplicates
	for (int i=0; i<=size-(size/2); i+=2){
		if (strarray[i]==strarray[i+2])
		{
			strarray[i+2].erase(0,strarray[i+2].size());
			strarray[i+3].erase(0,strarray[i+3].size());
		}
	}

	// remove blank components
	    for (int i=0; i<size; i++)
	    if (strarray[i]=="")
	    {
	        for (int j=i; j<size-1; j++)
	        	strarray[j]=strarray[j+1];

	        size--;
	        i--;
	    }
Last edited on
You are not using erase() properly. Try looking at the description/example uses of the function here:
http://www.cplusplus.com/reference/vector/vector/erase/
Ask again if you have trouble using the function after looking through that.
There are many other ways to remove duplicates and most of them are not found in the algorithms library. For example:

std::set, unordered_set, std::map, unordered_map. Of course you can decide to create a binary search tree that only supports inserting and traversal. Then simply put all your entries into the tree and later on, traverse the tree and put everything in a vector
Topic archived. No new replies allowed.