jeudi 29 avril 2021

Random shuffle function works in main(), but not a class

I'm attempting to use a seeded random_shuffle to simply shuffle a vector, before I use it. I tested this out by doing

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <bits/stdc++.h>


using namespace std;

int seed;
int rng(int i)
{
    srand(seed);
    return rand()%i;
}
int main()
{
    vector<int> myVec;
    cin >> seed;

for (int i = 0; i < 10; ++i)
    myVec.push_back(i);

for (auto it = myVec.begin(); it != myVec.end(); ++it)
    cout << *it;
cout << endl;
random_shuffle(myVec.begin(), myVec.end(), rng);

for (auto it = myVec.begin(); it != myVec.end(); ++it)
    cout << *it;
}

and it worked just fine. This lets me enter an int for the seed, and then prints out the before and after. However, when I tried to insert it into a class and run a build task with VSCode, it exploded.

class Test
{
public:
    Test(int seed)
    {
        random = seed;
        for (int i = 0; i < 10; ++i)
        myVec2.push_back(i);

       random_shuffle(myVec2.begin(), myVec2.end(), r);

    }
private:
    vector<int> myVec2;
    int random;

    int r(int i)
    {
        srand(random);
        return rand()%i;
    }
};

Here's the errors that came up:

25:54 required from here
error: must use '.*' or '->*' to call pointer-to-member function in '__rand (...)', e.g. '(... ->* __rand) (...)'
 4619 |    _RandomAccessIterator __j = __first + __rand((__i - __first) + 1);

Why is random_shuffle functioning correctly in main(), but not a class?




Aucun commentaire:

Enregistrer un commentaire