简体   繁体   中英

C++ Problems with arrays, begin and end in functions

Hello I am trying to write a script that picks a random number and then excludes that number afterwards.

#include <iostream>
#include <ctime>
#include <random>
#include <iterator>

using namespace std;

random_device rd;   // non-deterministic generator
mt19937 gen(rd());  // to seed mersenne twister.
uniform_int_distribution<> dist(1, 52); // distribute results between 1 and 6 inclusive.

int testFunc(int cardArray, int cardArray2, int k) {
    cardArray[k] = dist(gen);

    copy(begin(cardArray), end(cardArray), begin(cardArray2));
    cardArray2[k] = 0;

    bool exists = find(begin(cardArray2), end(cardArray2), cardArray[k]) != end(cardArray2);

    cardArray[k] = dist(gen);

    cout << i + 1 << ": " << cardArray[k] << "    " << exists << endl;

    return 0;
}

int main()
{
    int cardArray[52] = { 0 };
    int cardArray2[52] = { 0 };
    int i = 0;

    for (int n = 0; cardArray[n] == 0 && n < 52; n++) {

        cardArray[i] = dist(gen);

        copy(begin(cardArray), end(cardArray), begin(cardArray2));
        cardArray2[i] = 0;

        bool exists = find(begin(cardArray2), end(cardArray2), cardArray[i]) != end(cardArray2);

        cardArray[i] = dist(gen);

        cout << i + 1 << ": " << cardArray[i] << "    " << exists << endl;
        i++;
    }
    cout << endl;
    cin.ignore();
    return 0;
}

So there's a few problems so far. Here are the errors:

no instance of overloaded function "end" matches the argument list

no instance of overloaded function "begin" matches the argument list

expression must have pointer - to - object type

I just can't figure out what's wrong. The function itself works fine if it's just in main but I need to be able to call it.

Please tell me if I need to post more information.

You are taking in int s in you function not int*

int testFunc(int cardArray, int cardArray2, int k)

should be

int testFunc(int* cardArray, int* cardArray2, int k)

Unfortunately this will stop std::begin and std::end from working as they need an array and not a pointer. To pass the arrays to function you need to take them by reference. To do that we can use a template like:

template<typename T, std::size_t N, std::size_t M>
int testFunc(T (&cardArray)[N], T (&cardArray2)[M], int k)

Or we can skip using native arrays and use a std::array or std::vector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM