+ 2

Remove duplicates from a vector of structs

Say I have a structure with two members, name and date, and a vector of the structure declared. I'm tryna get rid of all duplicate objects in which the name member is not unique, and keep only one. What's the simplest way to solve this problem?

17th Aug 2018, 4:07 PM
Moses Odhiambo
Moses Odhiambo - avatar
5 Réponses
+ 2
You can copy your vector to a set, which automatically removes duplicates during the initialization process, and then copy your set's contents back to the vector. Note that if you want this to work your way, you will have to provide an overload for the == operator in your class. Or you can use the erase() function combined with unique(), which requires the vector to be sorted though. www.cplusplus.com/reference/algorithm/unique
17th Aug 2018, 5:41 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Moses Odhiambo is vector (which is input ) in your control? if yes, use map with name as key to avoid duplicate value as input itself.... if it is not in your control, iterator through vector elements and for each element , compare name with entire vector name...if match is found, erase current elemnt from vector..
17th Aug 2018, 4:33 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta So what happens when you try to add a duplicate value as the key? (in a map)
17th Aug 2018, 4:45 PM
Moses Odhiambo
Moses Odhiambo - avatar
0
Moses Odhiambo it override previous value
17th Aug 2018, 4:50 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Moses Odhiambo if input is in your control, take a look at below sample code for whatever I described for map: #include <iostream> using namespace std; #include<map> int main() { map<string,int> MyMap; MyMap["abc"] = 1; cout << MyMap.begin()->second << endl; // prints 1 MyMap["abc"] = 10; cout << MyMap.begin()->second; // prints 10 return 0; }
17th Aug 2018, 4:57 PM
Ketan Lalcheta
Ketan Lalcheta - avatar