Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- typedef int (*unary_predicate) (const void *elem);
- /**
- * Finds first element in the array that satisfies specific criteria
- * @param base Specifies base address of array
- * @param nmemb Specifies number of elements in the array
- * @param size Specifies size in bytes of each element in the array
- * @param pred Specifies predicate used to determining what to search
- * @returns index of found element, or @nmemb if no elements found
- */
- static size_t
- find_if(void *base, size_t nmemb, size_t size, unary_predicate pred)
- {
- for (size_t i = 0; i < nmemb; i++) {
- const void *elem = (const unsigned char *)base + size * i;
- if (!pred(elem)) {
- return i;
- }
- }
- return nmemb;
- }
- /**
- * Removes all elements satisfying specific criteria from the array.
- * @param base Specifies base address of array to remove from
- * @param nmemb Specifies number of elements in the array
- * @param size Specifies size in bytes of each element in the array
- * @param pred Specifies predicate used to determine what to remove
- * @returns new array size
- */
- static size_t
- remove_if(void *base, size_t nmemb, size_t size, unary_predicate pred)
- {
- size_t result = find_if(base, nmemb, size, pred);
- for (size_t i = result + 1; i < nmemb; i++) {
- const void *elem = (const unsigned char *)base + size * i;
- if (!pred(elem)) {
- void *dest = (unsigned char *)base + size * result;
- memcpy(dest, elem, size);
- result += 1;
- }
- }
- return result;
- }
Add Comment
Please, Sign In to add comment