【发布时间】:2025-12-04 13:40:01
【问题描述】:
我编写了一个生成唯一随机数的小程序。我首先使用我所知道的数组编写它来加载和打印数字。我正在尝试用向量替换数组,所以如果我想制作列表的副本,我可以更容易地做到这一点。我遇到了一个错误。
error: cannot convert 'std::vector<int>' to "std::vector<int>*' for argument '1' to bool numInList(std::vector<int>*, int)'
当我调用 numInList 函数时会发生此错误。
我是使用向量的新手,但我认为您可以使用像数组这样的向量,其优点是内置函数、没有固定大小以及能够将一个向量复制到另一个向量中。
这是我的代码:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
bool numInList(vector <int> randNumbers[], int num);
const int length = 100;
int main()
{
int countCheck = 0;
vector <int> randNumbers(length);
vector <int> newlist();
srand(time(0));
while(countCheck < length){
int num = rand() % 90000 +10000;
if (!numInList(randNumbers, num)){
randNumbers[countCheck] = num;
cout << "The Random Number " << randNumbers[countCheck] << endl;
countCheck++;
}
}
cout << "\n\n\n";
newlist[] = randNumbers[];
return 0;
}
bool numInList(vector<int> randNumbers[], int num){
for (int index = 0; index < length; index++){
if (randNumbers[index] == num){
return true;
}
}
return false;
}
我尝试取消引用希望能解决问题
if (!numInList(&randNumbers, num))
然后我在函数 numInList 中的 IF 语句上收到错误
error: ISO C++ forbids comparisons between pointers and integer [f-permissive]
任何帮助将不胜感激。
我已经更改了一些东西,现在我没有收到任何编译错误,但是程序在执行时崩溃了......有什么建议吗???
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
bool numInList(vector <int> randNumbers, int num);
const int length = 100;
int main()
{
int countCheck = 0;
vector <int> randNumbers;
vector <int> newlist;
srand(time(0));
while(countCheck < length){
int num = rand() % 90000 +10000;
if (!numInList(randNumbers, num)){
randNumbers.push_back(num);
cout << "The Random Number " << randNumbers[countCheck] << endl;
countCheck++;
}
}
cout << "\n\n\n";
newlist = randNumbers;
return 0;
}
bool numInList(vector<int> randNumbers, int num){
for (int index = 0; index < length; index++){
if (randNumbers[index] == num){
return true;
}
}
return false;
}
【问题讨论】:
-
vector <int> randNumbers[]将randNumbers声明为 of 个向量的数组。或者实际上,作为指向向量的指针,因为它是一个函数参数。newlist[] = randNumbers[]也应该只是newlist = randNumbers。 -
Zenith,你将如何正确声明向量?我尝试删除括号 [ ],但我得到了同样的错误。
-
@bryan,在函数的声明和定义中进行。
-
如果您不想重复,为什么不使用
std::set<int>而不是向量?如果你这样做了,numInList就不需要了。 -
感谢 Zenith,我需要休息一下,我认为您的解决方案很有意义,我会尝试一下。