asmcriminal asmcriminal - 1 year ago 84
C++ Question

How to remove unique values from a vector and keep duplicates


I am trying to remove all unique values from a vector. Below is my program output of the vector. The strings that I want to keep in the vector are in the grey box.

ART-105-1129 Spring 2004

FILM-298-1129 Spring 2004

GEOG-298-1370 Spring 2004

MUSLT-110-1370 Spring 2004

BCA-298-1617 Spring 2004

HIST-120-1617 Spring 2004

COMM-120-5008 Summer 2016

ANTHR-140-5306 Fall 2016

ENGL-122-5355 Fall 2016

The code I want to keep has matching strings after the second "-".

The code I used for the above output is.

set<string> s(listOfCourses.begin(), listOfCourses.end());
listOfCourses.assign(s.begin(), s.end());

set<string> dupremove(duplicateTermsAndSections.begin(), duplicateTermsAndSections.end());
duplicateTermsAndSections.assign(dupremove.begin(), dupremove.end());

for (vector<string>::iterator itouter = duplicateTermsAndSections.begin(); itouter!= duplicateTermsAndSections.end(); itouter++) !copyDuplicateTermsAndSections.empty(); copyDuplicateTermsAndSections.pop())
for (vector<string>::iterator it = listOfCourses.begin(); it != listOfCourses.end(); it++)
if ((*it).find(*itouter) != string::npos)
cout << *it << endl;
cout << endl;

I want to remove strings that do not have a matching term. A matching term is like the 2 strings below. They both have a matching "-1129 Spring 2004" in them.

ART-105-1129 Spring 2004

FILM-298-1129 Spring 2004

Below are 2 unmatching terms they do not have the same substring(as above)

ANTHR-140-5306 Fall 2016

ENGL-122-5355 Fall 2016

Answer Source

If you compute a frequency map where the keys are your substring you are extracting between the second '-' and the following space. As you iterate over your collection of strings, look at the map. If the key is not yet in the map, put a value of 1 in the map for that key. If the key is in the map, increment the value stored in the map that corresponds to the map.

Then, make a second pass through the collection of strings, if the extracted substring has a corresponding value of 1 in the map, it is unique, otherwise it is a duplicate.

I'll leave it as an exercise for you to work the C++ specific syntax for the above described algorithm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download