Reputation: 846
I have a list of the following structure
struct Element
{
int id;
int groupID;
};
I want to know how many unique groups there are
for example
list<Element> myElements;
Element e;
e.id = 0;
e.groupID = 2;
myElements.push_back(e);
e.id = 1;
e.groupID = 0;
myElements.push_back(e);
e.id = 2;
e.groupID = 2;
myElements.push_back(e);
e.id = 3;
e.groupID = 1;
myElements.push_back(e);
There are 4 elements here but only 3 unique group ids 0, 1, 2
I'm trying to look for an efficient way to do that because my list grows in size.
I tried this
struct groupID_unique {
bool operator() (Element first, Element second)
{ return (first.groupID != second.groupID); }
};
myElements.unique(groupID_unique());
But this returns to me the 2 un-repetitive ids 0,1
Upvotes: 0
Views: 1039
Reputation: 20383
Use a set to store the items (temporarily). A set will store only the unique items. The size of the set is the number of unique items.
Add an equality comparator for the object:
struct Element {
bool operator==(Element const& rhs) const {
return id == rhs.id && groupId == rhs.groupId;
}
};
Use a set
.
std::set<Element> elementSet{elementList.begin(), elementList.end()};
size_t const numUniqueElements = elementSet.size();
Note that there is some cost (time and space complexity) in constructing the set
. If you want to keep the repetitions for some other purpose, then you can continue with the list
otherwise you can switch from the list
and set
so that you always have the unique count readily available (through .size()
)
Upvotes: 2