我一直在試圖讓我的C++程序檢查數組中的重複項,因爲我需要這個程序來編寫程序。但是,它不起作用,我想我知道這個問題是怎麼回事,但我不知道如何解決它。如何確保數組中沒有重複項?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
int asknum(int ask);
int check(int checking);
bool error = false;
int test [10] = {};
int i = 0;
int gen = 0;
int main() {
//int gen = 0;
for (i=0; i<10; i++) {
gen = asknum(gen);
}
for (int b=0; b<10; b++) {
cout << test [b] << endl;
}
return 0;
}
int asknum(int ask) {
ask = 0;
gen = 0;
int nouse;
cout << "Please enter a value: ";
cin >> ask;
error = 0;
nouse = check(ask);
}
int check(int checking) {
int n = 0;
for (n=0; n<10; n++) {
int temp = test [n];
if (temp == checking) {
cout << "Value is the same. Enter another value.\n";
error = 1;
gen = asknum(gen);
}
}
if (n == 10) {
if (error == 0) {
gen = 0;
test [i] = checking;
}
}
}
我的代碼有什麼問題?我第一次編寫代碼時,它的工作很完美。但是當我注意到一個缺陷,那就是如果你經常輸入一個現在的數字,它會停止詢問一個新的數字,我決定把代碼移入函數,但現在它不能正常工作!這裏是輸出:
Please enter a number: 1
Please enter a number: 2
Please enter a number: 3
Please enter a number: 3
That number already is used. Please type in another value.
Please enter a number: 4
Please enter a number: 5
Please enter a number: 6
Please enter a number: 7
Please enter a number: 8
Please enter a number: 9
Please enter a number: 10
1
2
3
3
5
6
7
8
9
10
我認爲通信有問題。請幫忙!
謝謝!
使用'std :: set'來保證容器不會包含重複項。 – user0042
我會在哪裏放置? –
而不是'int test [10] = {};':'std :: set test;'你的代碼需要更多的適配。 –
user0042