Efficient way to find frequencies of each unique value in the std::vector

前端 未结 4 572
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-19 18:58

Given a vector std::vector v, we can find unique elements efficiently by:

std::vector uv(v.begin(), v.end());
std::         


        
4条回答
  •  逝去的感伤
    2021-01-19 19:37

    using equal_range:

    std::vector results;
    for(auto i = begin(v); i != end(v);)
    {
        auto r = std::equal_range(i, end(v), *i);
        results.emplace_back( std::distance(r.first, r.second) );
        i = r.second;
    }
    

    SSCCE:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::vector v{1.0, 2.0, 1.0, 2.0, 1.0, 3.0};
        std::sort(begin(v), end(v));
    
        std::vector results;
        for(auto i = begin(v); i != end(v);)
        {
            auto r = std::equal_range(i, end(v), *i);
            results.emplace_back( std::distance(r.first, r.second) );
            i = r.second;
        }
    
        for(auto const& e : results) std::cout << e << "; ";
    }
    

提交回复
热议问题