Search code examples
c++stdvectorstl-algorithm

Counting and retrieving repetition using algorithm and lambda


I have a vector of structs like this:

struct Item {
   int id;
   string name;   
}

vector<Item> v= ....;

Now I need to see how many unique "id" are in the vector and create another vector that contains these unique ids (of course 1 of each ids).

For countig unique ids I use this code...but how to generate a vector of unique ids?

std::sort(v.begin(), v.end());
int uniqueCount = std::unique(v.begin(), v.end()) - v.begin();

Of course I can go old school and do a loop and put ids in a vector manually while checking if the id is already inside the vector or not...but I am looking for a clean STL approach if possible!


Solution

  • One possible approach with STL and lambda is following one where unique_ids is a vector of unique ids.

    DEMO

    std::sort(
        v.begin(), v.end(), 
        [](const Item& l, const Item& r){ return (l.id < r.id);});
    
    v.erase(
        std::unique(v.begin(), v.end(), 
            [](const Item& l, const Item& r) { return l.id == r.id; }),
        v.end());
    
    std::vector<int> unique_ids;
    
    std::transform(
        v.begin(), v.end(), std::back_inserter(unique_ids),        
        [](const Item& item){ return item.id; });