Search code examples
c++randomboostc++14

Is there a std::sample equivalent in boost?


I'm still using C++14. So std::sample is out of reach. Is there something equivalent in boost? I do not want to copy my std::multiset which isn't reorderable.


Solution

  • As far as I know, there is not such a thing in boost. But you may write a simple one, yourself:

    template<typename T>
    std::vector<T> sample_items(const std::multiset<T> & ms, int samples) 
    {
       std::vector<T> ret_value;
       std::random_device rd;
       std::mt19937 gen(rd());
       std::uniform_int_distribution<> dis(0, ms.size() - 1);
    
       for (int i = 0; i < samples; i++)
       {
          auto first = std::begin(ms);
          auto offset = dis(gen);
    
          std::advance(first, offset);
          ret_value.push_back(*first);
       }
    
       return ret_value;
    }
    

    I do not want to copy my std::multiset which isn't reorderable.

    If still prefer not to send your multiset to a function, just change the function in order to work with iterators.