c++ - Unique list of structure -
i have list of following structure
struct element { int id; int groupid; }; i want know how many unique groups there
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 4 elements here 3 unique group ids 0, 1, 2
i'm trying efficient way because list grows in size.
i tried
struct groupid_unique { bool operator() (element first, element second) { return (first.groupid != second.groupid); } }; myelements.unique(groupid_unique()); but returns me 2 un-repetitive ids 0,1
use set store items (temporarily). set store unique items. size of set number of unique items.
add equality comparator object:
struct element { bool operator==(element const& rhs) const { return id == rhs.id && groupid == rhs.groupid; } }; use set.
std::set<element> elementset{elementlist.begin(), elementlist.end()}; size_t const numuniqueelements = elementset.size(); note there cost (time , space complexity) in constructing set. if want keep repetitions other purpose, can continue list otherwise can switch list , set have unique count readily available (through .size())
Comments
Post a Comment