std :: vector를 섞는 방법?
std::vector
C ++에서 셔플하는 일반적인 재사용 가능한 방법을 찾고 있습니다. 이것이 내가 현재하는 방법이지만 중간 배열이 필요하고 항목 유형을 알아야하기 때문에 매우 효율적이지 않다고 생각합니다 (이 예에서는 DeckCard).
srand(time(NULL));
cards_.clear();
while (temp.size() > 0) {
int idx = rand() % temp.size();
DeckCard* card = temp[idx];
cards_.push_back(card);
temp.erase(temp.begin() + idx);
}
C ++ 11부터는 다음을 선호해야합니다.
#include <algorithm>
#include <random>
auto rng = std::default_random_engine {};
std::shuffle(std::begin(cards_), std::end(cards_), rng);
매번 다른 순열을 생성하려는 경우 rng
여러 호출 에서 동일한 인스턴스를 재사용해야합니다 std::shuffle
!
또한 프로그램이 실행될 때마다 다른 순서의 셔플을 생성하도록하려면 임의 엔진의 생성자에 std::random_device
.
C ++ 98의 경우 다음을 사용할 수 있습니다.
#include <algorithm>
std::random_shuffle(cards_.begin(), cards_.end());
http://www.cplusplus.com/reference/algorithm/shuffle/
// shuffle algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <vector> // std::vector
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
int main ()
{
// obtain a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine e(seed);
while(true)
{
std::vector<int> foo{1,2,3,4,5};
std::shuffle(foo.begin(), foo.end(), e);
std::cout << "shuffled elements:";
for (int& x: foo) std::cout << ' ' << x;
std::cout << '\n';
}
return 0;
}
@Cicada가 말한 것 외에도 먼저 씨를 뿌려야합니다.
srand(unsigned(time(NULL)));
std::random_shuffle(cards_.begin(), cards_.end());
@FredLarson의 의견에 따라 :
the source of randomness for this version of random_shuffle() is implementation defined, so it may not use rand() at all. Then srand() would have no effect.
So YMMV.
If you are using boost you could use this class (debug_mode
is set to false
, if you want that the randomizing could be predictable beetween execution you have to set it to true
):
#include <iostream>
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <algorithm> // std::random_shuffle
using namespace std;
using namespace boost;
class Randomizer {
private:
static const bool debug_mode = false;
random::mt19937 rng_;
// The private constructor so that the user can not directly instantiate
Randomizer() {
if(debug_mode==true){
this->rng_ = random::mt19937();
}else{
this->rng_ = random::mt19937(current_time_nanoseconds());
}
};
int current_time_nanoseconds(){
struct timespec tm;
clock_gettime(CLOCK_REALTIME, &tm);
return tm.tv_nsec;
}
// C++ 03
// ========
// Dont forget to declare these two. You want to make sure they
// are unacceptable otherwise you may accidentally get copies of
// your singleton appearing.
Randomizer(Randomizer const&); // Don't Implement
void operator=(Randomizer const&); // Don't implement
public:
static Randomizer& get_instance(){
// The only instance of the class is created at the first call get_instance ()
// and will be destroyed only when the program exits
static Randomizer instance;
return instance;
}
template<typename RandomAccessIterator>
void random_shuffle(RandomAccessIterator first, RandomAccessIterator last){
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > random_number_shuffler(rng_, boost::uniform_int<>());
std::random_shuffle(first, last, random_number_shuffler);
}
int rand(unsigned int floor, unsigned int ceil){
random::uniform_int_distribution<> rand_ = random::uniform_int_distribution<> (floor,ceil);
return (rand_(rng_));
}
};
Than you can test it with this code:
#include "Randomizer.h"
#include <iostream>
using namespace std;
int main (int argc, char* argv[]) {
vector<int> v;
v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);v.push_back(5);
v.push_back(6);v.push_back(7);v.push_back(8);v.push_back(9);v.push_back(10);
Randomizer::get_instance().random_shuffle(v.begin(), v.end());
for(unsigned int i=0; i<v.size(); i++){
cout << v[i] << ", ";
}
return 0;
}
참고URL : https://stackoverflow.com/questions/6926433/how-to-shuffle-a-stdvector
'Programing' 카테고리의 다른 글
현재 컨텍스트에 'ViewBag'이름이 없습니다.-Visual Studio 2015 (0) | 2020.09.16 |
---|---|
Python에서 매우 긴 If 문 (0) | 2020.09.16 |
"iTunes Store에 연결할 수 없습니다"인앱 구매 (0) | 2020.09.16 |
bash에서 스크립트에 선언 된 변수를 나열하는 방법은 무엇입니까? (0) | 2020.09.16 |
ASP.NET MVC의 부분보기에 매개 변수를 전달하는 방법은 무엇입니까? (0) | 2020.09.16 |