Software > Software

comparing arrays, easy one but im a student, C++

(1/2) > >>

sseb4:
hey i need a way of comparing say 1 array eg n[10] to predetermined arrays that matches n[10]. n[10] will be scanned/input into the program. How could i do this in C++. would strcmp or memcmp work? i dont really know how to use memcmp as i dont hae a copy of a compiler for C++ at home. Please give me an example of how to do this

Nyx:
I'm pretty sure std::vector defines an operator ==.... So if you use that container, you can just compare all elements at once with that. Otherwise, just use a for loop and compare each individual element. If one does not match, then the arrays don't have the same content.

MadMax:
My solution would be as following


--- Code: ---bool CompareArrays() {
  for(int x = 0; x < 10; x++) {
    if(array1[x] != array2[x]) {
      return false;
    }
  }
  return true;
}

void main() {
  if(CompareArrays == true) {
    print("wooohoooo");
  }
  //not sure about the 'print' command, I'm a C++ coder, so I use cout<< "blabla";
}
--- End code ---

rgcustodio:

--- Quote ---would strcmp or memcmp work?
--- End quote ---
definitely :)

Make sure though that your both arrays use the same data type. No use in doing a compare if one of your arrays contains 2-byte shorts and the other contains 1-byte chars.


--- Quote ---MEMCMP(3)                           NEWLIB                           MEMCMP(3)

NAME
       6.7 `memcmp'--compare two memory areas

SYNOPSIS
            #include <string.h>
            int memcmp(const void *S1, const void *S2, size_t N);

DESCRIPTION
       This function compares not more than N characters of the object pointed
       to by S1 with the object pointed to by S2.

RETURNS
       The function returns an integer greater than, equal  to  or  less  than
       zero    according  to  whether  the  object pointed to by S1 is greater
       than, equal to or less than the object pointed to by S2.

PORTABILITY
       `memcmp' is ANSI C.

          `memcmp' requires no supporting OS subroutines.

SEE ALSO
       memcmp is part of the libc library.  The full documentation for libc is
       maintained  as  a  Texinfo  manual.   If  info  and  libc  are properly
       installed at your site, the command

              info libc

       will give you access to the complete manual.

NEWLIB                            2006 Aug 09                        MEMCMP(3)

--- End quote ---

Admin:

--- Code: ---if(array1[x] != array2[x]) {
      return false;}
--- End code ---
hmmm i would have just done a for loop cause im a noob like that . . .
does that also work in C, or just C++?

Navigation

[0] Message Index

[#] Next page

Go to full version