Your solution has time complexity O(n*n) but the problem can be solved with complexity O(n*log(n)) or even O(n).
First, let's define such category comparison function (if a category is "Land" or "Jungle" then it's greater then other categories):
bool CategoryLess(string sCategory1, string sCategory2){
return sCategory1 != "Land" && sCategory1 != "Jungle"
&& (sCategory2 == "Land" || sCategory2 == "Jungle");
}
Now iterate through the vector and store all found subcategories and corresponding Subjects in a std::unordered_map
(or std::map
in if you don't use C++11). If the subcategory is already in the map
then replace corresponding Subject
if the category of the already found Subject
less then category of the new Subject
:
unordered_map<string, Subject*> Subcategories;
for (int i=0; i<sub_vec.size(); ++i){
unordered_map<string, Subject*>::iterator
it = Subcategories.find(sub_vec[i].get_sub_category());
if (it != Subcategories.end()){
if (CategoryLess((*it)->get_category(), sub_vec[i].get_category())
it->second = &sub_vec[i];
}
else
Subcategories[sub_vec[i].get_sub_category()] = &sub_vec[i];
}
Now you have the map of all subcategories and corresponding Subject
s.
If we found two or more Subject
s with the same subcategory then the map contains a pointer to the Subject
with greater category.
Now iterate sub_vec once more and delete Subject
s if
Subcategories[sub_vec[i].get_sub_category()] != &sub_vec[i];
Time complexity:
If we use std::unordered_map
then expected time complexity is O(n) for the both cycles (O(n*n) in worst case).
If we use std::map
then time complexity is O(n*log(n)) for the both cycles.
(I didn't take into account time complexities of string comparison and vector.erase as irrelevant)
Please note than when you delete a Subject
from the vector, the addresses of other Subject
s can be changed. So you need to take care when compare pointers to Subject
s (for example copy needed Subject
s to another vector instead of deleting other Subject
s from the vector). But it doesn't change the general idea of my solution.