This is a small utility that permutes a C++ standard container without modifying the container being iterated:
random_iterator.hpp
#ifndef RANDOM_ITERATOR_HPP
#define RANDOM_ITERATOR_HPP
#include <initializer_list>
#include <random>
#include <vector>
namespace net {
namespace coderodde {
namespace utilities {
template<typename T>
class random_iterator {
private:
std::vector<T> vec;
public:
template<typename Iterable>
explicit random_iterator(Iterable iterable)
{
for (auto& x : iterable)
{
vec.push_back(x);
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(vec.begin(), vec.end(), g);
}
template<typename Iterable>
explicit random_iterator(Iterable iterable, std::random_device& rd)
{
for (auto& x : iterable)
{
vec.push_back(x);
}
std::mt19937 g(rd());
std::shuffle(vec.begin(), vec.end(), g);
}
explicit random_iterator(std::initializer_list<T>& lst)
{
for (auto& x : lst)
{
vec.push_back(x);
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(vec.begin(), vec.end(), g);
}
explicit random_iterator(std::initializer_list<T>& lst,
std::random_device& rd)
{
for (auto& x : lst)
{
vec.push_back(x);
}
std::mt19937 g(rd());
std::shuffle(vec.begin(), vec.end(), g);
}
typename std::vector<T>::iterator begin()
{
return vec.begin();
}
typename std::vector<T>::iterator end()
{
return vec.end();
}
typename std::vector<T>::const_iterator begin() const
{
return vec.cbegin();
}
typename std::vector<T>::const_iterator end() const
{
return vec.cend();
}
};
} // End of net::coderodde::utilities
} // End of net::coderodde
} // End of net
#endif // RANDOM_ITERATOR_HPP
main.cpp
#include "random_iterator.hpp"
#include <iostream>
#include <set>
#include <vector>
using namespace std;
using net::coderodde::utilities::random_iterator;
int main(int argc, const char * argv[]) {
vector<int> v1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto& x : random_iterator<int>(v1))
cout << x << " ";
cout << "\n";
set<int> s1 {1, 2, 3, 4, 5};
for (auto& x : random_iterator<int>(s1))
cout << x << " ";
cout << "\n";
}
Critique request
I would like to know, how a professional C++ programmer would implement this.
shuffled_vector
. \$\endgroup\$ – zett42 Jun 9 '17 at 18:29namespace std;
you can clash with. \$\endgroup\$ – Baum mit Augen Jun 9 '17 at 23:36