Skip to content

Commit

Permalink
feature: Implemented Helper::setElement()
Browse files Browse the repository at this point in the history
This helper function can be used to get random items from a std::set
of objects.
  • Loading branch information
braw-lee committed Nov 21, 2023
1 parent bc2f7c8 commit c6a368f
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions include/faker-cxx/Helper.h
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#pragma once

#include <algorithm>
#include <functional>
#include <numeric>
#include <set>
#include <span>
#include <string>

Expand Down Expand Up @@ -67,6 +69,32 @@ class Helper
return data[index];
}

/**
* @brief Get a random element from a std::set.
*
* @tparam T an element type of the std::set.
*
* @param std::set of elements.
*
* @return T a random element from the std::set.
*
* @code
* std::set<char> chars{'a', 'b', 'c', 'd', 'e'};
* Helper::setElement(chars) // 'd'
* @endcode
*/
template <class T>
static T setElement(const std::set<T>& data)
{
if (data.empty())
{
throw std::invalid_argument{"Data is empty."};
}
T item;
std::sample(data.begin(), data.end(), &item, 1, pseudoRandomGenerator);
return item;
}

template <class T>
struct WeightedElement
{
Expand Down

0 comments on commit c6a368f

Please sign in to comment.