I prefer to use shuffle.
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
#include <cassert>
class T455_t
{
private:
// data
std::vector<int> m_iVec ;
public:
T455_t() {}
int exec()
{
std::vector<int> iVec;
gen10();
for (int i=0; i<10; ++i)
{
int nxtRandom = uniqueRandomInt();
std::cout << nxtRandom << std::endl;
}
return(0);
}
private: // methods
void gen10() // fills data attribute with 10 digits
{
for (int i=0; i<=9; ++i)
m_iVec.push_back(i);
std::random_device rd;
std::mt19937_64 gen(rd());
std::shuffle (m_iVec.begin(), m_iVec.end(), gen);
// m_iVec now contains 10 unique numbers,
// range 0..9, in random order
}
int uniqueRandomInt()
{
assert(m_iVec.size());
int retVal = m_iVec.back(); // gets last element in vector
m_iVec.pop_back(); // removes last element
return(retVal);
}
}; // class T455_t
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "");
std::ios::sync_with_stdio(false);
std::chrono::high_resolution_clock::time_point m_start_us =
std::chrono::high_resolution_clock::now();
int retVal = -1;
{
T455_t t455;
retVal = t455.exec();
}
std::chrono::microseconds chrono_duration_us =
std::chrono::duration_cast <std::chrono::microseconds>
(std::chrono::high_resolution_clock::now() - m_start_us);
std::cout << " FINI " << chrono_duration_us.count()
<< " us" << std::endl;
return(retVal);
}
2
solved Unique Random Number between 0 and 9