[英]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
没有重载函数“ end”的实例与参数列表匹配
no instance of overloaded function "begin" matches the argument list
没有重载函数“ begin”的实例与参数列表匹配
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.
如果仅在main中,则函数本身可以正常工作,但我需要能够对其进行调用。
Please tell me if I need to post more information. 请告诉我是否需要发布更多信息。
You are taking in int
s in you function not int*
您正在使用
int
而不是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. 不幸的是,这将使
std::begin
和std::end
工作,因为它们需要数组而不是指针。 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
或者我们可以跳过使用本机数组,而使用
std::array
或std::vector
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.