2017-09-13 116 views
-1

我知道有一種方法來檢查值是否在一個數組中,但是有沒有辦法來檢查一個值是否不是 ?有沒有辦法來檢查一個int是否不等於數組中的所有值? (C++)

這段代碼將檢查每個索引,但是當它進入下一個索引時將忽略過去的索引。 (即有沒有檢查該vary_result代碼!=「中的所有值陣」?)

int buffer; //all variables 
int vary_result; 
int range; 
int minimum_value; 
for(int j = 0; j < buffer; j++) { 
    if(vary_result == buffer_array[j]){ 
     vary_result = rand() % range + minimum_value; // creates a random value and saves it at vary_result 
     }; 
    }; 
cout << vary_result << endl; 
+3

'vary_result = rand()%range + minimum_value'是什麼意思?這似乎與所述目標沒有任何關係 – Carcigenicate

+0

檢查數值是否在數組中,調用結果'x',然後檢查它是否不在數組中是'!x'。 – user463035818

+4

['std :: none_off'](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of) – NathanOliver

回答

4

我知道有一種方法來檢查值是一個數組,但有一個方法來檢查一個值是不是?

二隻是相對於第一:

auto begin = buffer_array; 
auto end = buffer_array + buffer; 
auto it = std::find(begin, end, value); 
if(it == end) // value not found which means none of the elements equal to value, which means value is not in array 
    // do whatever, but do not dereference it 
2

是有測試一個值不是在陣列中的一種方式。下面是我是如何做到的:

bool valueInArray; 
bool valueNotInArray = true; 
int valueToTest = 10; 
int valuesArray[] = [1, 2, 3, 5, 9]; 


for(int i = valuesArray.length(); i <= valuesArray.length(); i++) { 
if(valueToTest == valuesArray[i]) 
    notInIt == false; 
} 

if (notInIt == false) 
    valueInArray = true; 
else 
    valueInArray = false; 

本質上,我創建了兩個布爾值,一個要測試的數字和一個數組。我用for循環檢查數組是否在數組中。然後,我使用了一個if/else來設置另一個與前一個布爾值相反的布爾值。這樣,最終布爾值反映該值是否不在數組中。

+0

您的代碼有問題,比方說,如果數組的第二個值等於測試價值,而不是它會是假的。但是,如果數組的最後一個值不等於測試值,notIntIt將是真實的。因此,即使是這樣,測試變量看起來並不在數組中。 –

相關問題