问题
Suppose that I have an array
bool string[N]={false};
After doing some operations all the elements of the array string become true. And I want to check this condition in an if statement like so:-
pseudo code--
if(all the elements of string are same or equal)
then do this
How do I achieve this?I am not supposed to use counters like
for(int i=0;i<N;i++) //or something else like this
回答1:
PP just needed to alter his code a tiny bit, the answer he was alluding to was:-
if (memcmp (&string [0], &string [1], sizeof string [0] * (N - 1)) == 0)
{
/* all elements the same */
}
The N-1 stops overrunning the end of the buffer.
The memcmp compares string [0] with string [1], then string [1] with string [2], then string [2] with string [3] and so on up to string [n-2] and string [n-1].
回答2:
If you can use pointers, then it could be something like this:
bool first = string[0];
bool* current = string + 1;
bool* end = string + N;
bool allEqual = true;
while (current < end)
{
if (*current != first)
{
allEqal = false;
break; // No need to loop more
}
++current;
}
if (allEqual)
std::cout << "All elements are " << std::boolalpha << first << '\n';
else
std::cout << "First not-equal is at index " << (current - string) / sizeof(string[0]) << '\n';
Really not that much different than using an index, since the pointer current
acts as a kind of index.
回答3:
"I am not supposed to use counters like for(int i=0;i<N;i++)
" ~> you still need to write a loop that examines all elements, you just need to avoid using temporary int
variables for indexing.
int elementsAreEqual(int* first, int size) {
int* current = first;
int* last = first + size - 1;
while (1) {
if (*current != *first)
return 0;
if (current == last)
break;
current++;
}
return 1;
}
used as:
const int N = 5;
int values[] = {0,0,0,0,0};
if (elementsAreEqual(values, N))
printf("Elements are equal.\n");
else
printf("Elements are not equal.\n");
回答4:
If you want to check it with only one if, and no loop, you can try the following:
bool string[N] = {false};
if ((0 == memcmp(&string[0], &string[1], sizeof(string[0]) * (sizeof(string) - 1))) {
//equal
}
Because the two memory areas overlap, offset by one, then each pair in the array are compared.
来源:https://stackoverflow.com/questions/19033521/how-can-i-check-that-elements-of-an-array-are-all-same-without-using-counter