Guest User

Untitled

a guest
Sep 20th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. typedef int (*unary_predicate) (const void *elem);
  2.  
  3. /**
  4. * Finds first element in the array that satisfies specific criteria
  5. * @param base Specifies base address of array
  6. * @param nmemb Specifies number of elements in the array
  7. * @param size Specifies size in bytes of each element in the array
  8. * @param pred Specifies predicate used to determining what to search
  9. * @returns index of found element, or @nmemb if no elements found
  10. */
  11. static size_t
  12. find_if(void *base, size_t nmemb, size_t size, unary_predicate pred)
  13. {
  14. for (size_t i = 0; i < nmemb; i++) {
  15. const void *elem = (const unsigned char *)base + size * i;
  16. if (!pred(elem)) {
  17. return i;
  18. }
  19. }
  20. return nmemb;
  21. }
  22.  
  23. /**
  24. * Removes all elements satisfying specific criteria from the array.
  25. * @param base Specifies base address of array to remove from
  26. * @param nmemb Specifies number of elements in the array
  27. * @param size Specifies size in bytes of each element in the array
  28. * @param pred Specifies predicate used to determine what to remove
  29. * @returns new array size
  30. */
  31. static size_t
  32. remove_if(void *base, size_t nmemb, size_t size, unary_predicate pred)
  33. {
  34. size_t result = find_if(base, nmemb, size, pred);
  35. for (size_t i = result + 1; i < nmemb; i++) {
  36. const void *elem = (const unsigned char *)base + size * i;
  37. if (!pred(elem)) {
  38. void *dest = (unsigned char *)base + size * result;
  39. memcpy(dest, elem, size);
  40. result += 1;
  41. }
  42. }
  43. return result;
  44. }
Add Comment
Please, Sign In to add comment