1
所以我的程序應該使用一個5大小的數組來存儲輸入的整數。如果它是一個重複的整數,它將不會被存儲到數組中。如何忽略數組中的0並打印出唯一的數字
這裏的問題是我的數組中會有0的無限期,因爲我初始化的大小爲5.我只需要輸出唯一的數字我該怎麼做?
我注意到的一件事是,沒有我的無符號整型位置;每當我輸入一個重複的整數,它會跳過索引;
例如 array [0] = 10,array [1] = 10 // duplicate,array [2] = 20 //輸入20,它應該已經存儲到數組[1]中,但它沒有。 所以,我只有在不重複的情況下才會增加位置,以確保在輸入重複項時不會跳過索引。
有沒有什麼我可以做或做不同的方法來得到我的結果?
代碼:
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
const unsigned int MIN_VALUE = 10;
const unsigned int MAX_VALUE = 100;
const size_t arraySize = 5;
array <int, arraySize> numberArray = {};
template<size_t size>
bool isDuplicate(array<int, size> array, int value)
{
for (unsigned int i = 0; i < array.size(); i++)
{
if (value == array[i])
{
return true;
}
}
return false;
}
int main()
{
unsigned int input;
unsigned int position = 0;
for (unsigned int i = 0; i < arraySize; i++)
{
cout << "Enter # " << (i + 1) << " : ";
cin >> input;
if (input < MIN_VALUE || input > MAX_VALUE)
{
cout << "The number entered is not in valid range of 10 to 100" << endl;
--i;
}
else if (!isDuplicate(numberArray, input))
{
numberArray[position] = input;
position++;
cout << "The number: " << input << " is unique\n" << endl;
}
}
}
謝謝!
事情的要求是,當用戶輸入一個重複的號碼時,它會忽略它,所以它幾乎仍然遞增外部循環以提示用戶輸入**下一個#**。例如:輸入#1:10,輸入#2:10,然後輸入#3:20 .....它不會減少它,所以我最初的問題是,會有一點數組的索引根本不使用,因此它的0.我只需要打印出唯一的數字而不是0。謝謝! –
nevemind ...我知道了。我對於打印整個陣列的方式太在意,但我忘記了位置是跟蹤我正在使用的元素,我可能只是將位置打印出來。 Ahahaha感謝您的幫助!真的很感激它。 –
如果排序對你無關緊要,你可以看看'std :: unordered_set'這可能已經用更少的代碼行解決了你的問題:http://www.cplusplus.com/reference/unordered_set/unordered_set/ ?千瓦= unordered_set。 無論如何,不客氣。 ;) – WillCroPoint