Confrontare un int a un array di int Obj-C
-
26-09-2019 - |
Domanda
Come faccio a vedere se il mio intero è in un array di interi ...
es voglio sapere se 7 è in un array [1 3 4 5 6 7 8]
tutte le idee?
Grazie
Soluzione
Ci sono diversi modi per fare questo a seconda di fattori quali la dimensione della matrice -. Quanto spesso è necessario cercare, quanto spesso è necessario aggiungere alla matrice, ecc In generale si tratta di un problema informatico
In particolare direi ci sono tre opzioni probabile che meglio si adattano alle vostre esigenze.
- "forza bruta": basta scorrere l'array alla ricerca per il valore. Chiamando
containsObject:
sulNSArray
farà questo per voi. Semplice e probabilmente più veloce per le piccole dimensioni degli array. - Copia l'array in un set e l'uso
containsObject:
per controllare l'esistenza - Mantenere i valori nella matrice, ma ordinare l'array e implementare il proprio binario di ricerca - che probabilmente non è così complesso come sembra.
Altri suggerimenti
Questo dipende dal tipo di array che hai, se si tratta di un oggetto o un array di C. A giudicare dai vostri tag hai un NSArray con NSIntegers, questo sarebbe sbagliato. NSIntegers non sono oggetti e non può essere messo in un NSArray, a meno che non li avvolgono in un oggetto, ad esempio un NSNumber.
NSArray
Utilizzare il containsObject:
metodo
Non sono del tutto sicuro di come si mettono le interi in un NSArray. Il solito modo per farlo è quello di utilizzare NSNumber.
NSArray *theArray = [NSArray arrayWithObjects:[NSNumber numberWithInteger:1],
[NSNumber numberWithInteger:7],
[NSNumber numberWithInteger:3],
nil];
NSNumber *theNumber = [NSNumber numberWithInteger:12];
/*
* if you've got the plain NSInteger you can wrap it
* into an object like this:
* NSInteger theInt = 12;
* NSNumber *theNumber = [NSNumber numberWithInteger:theInt];
*/
if ([theArray containsObject:theNumber]) {
// do something
}
C-Array
ho il sospetto che si sta utilizzando un C-Array. In questo caso si deve scrivere il proprio ciclo.
NSInteger theArray[3] = {1,7,3}
NSInteger theNumber = 12;
for (int i; i < 3; i++) {
if (theArray[i] == theNumber) {
// do something
break; // don't do it twice
// if the number is twice in it
}
}
//assume these data, either from a method call or instance variables
int theArray[7] = {1,7,3,8,5,7,4};
int numberIWant = 8;
//this is the essence in a C-array, which you can easily use on ios
BOOL isNumberFound = NO;
for (int i; i < sizeof(theArray)/sizeof(int); i++) {
if (theArray[i] == numberIWant) {
isNumberFound = YES;
break; //breaks the for loop
}
}
//return the bool, or otherwise check the bool
if (isNumberFound)
{
//do stuff
}