Hot answers tagged

7

Long name ThorsAnvil::Util::getRandomIteratorFromContainer is a really long name. I suggest something like getRandomElement or even randomElement. Unnecessary function getDist seems kind of unnecessary to me. I think it would be cleaner to construct the distribution directly. std::uniform_int_distruction<int> dist{0, container.size() - 1}; Types ...


3

Instead of accepting a container, accept an iterator pair. We may want to use just part of a container (e.g. after using std::partition). In C++20, a standard forward_range view could be used. It probably makes sense to use different implementations for forward-access and random-access collections (there's a single-pass algorithm for selecting 1 out of an ...


3

In addition to Kerndog73's answer: Don't forget to check for an empty container to avoid undefined behavior. We should probably return the end() iterator in that case.


3

I have some suggestions to improve your code: Formatting You should use empty lines consistently. E.g. you have some ifs/else ifs blocks where you put an empty line at the beginning but not everywhere. I suggest you to not use empty lines there at all. You should not use more than two empty lines to seperate things. It's harder to read. You should put ...


2

I think you should clarify what you want. Depending on that, the answer will be slightly different. If you want an iterator to a random element then Kerndog's answer is really close: template <typename Container, typename Generator> auto random_iterator(Container &con, Generator &gen) { using std::begin; using std::size; std::...


Only top voted, non community-wiki answers of a minimum length are eligible