C Collections

citerators · Section 3

ccol_for_each

ccol_for_each - iterate over all elements of any supported container

C Collections (libccollections, -lccollections)

#include <ccollections/citerators.h>   /* or any container header */
 
ccol_for_each(container, it, { body });

ccol_for_each declares a cmap_iterator* named it with RAII cleanup, then
walks from ccol_begin(container) to NULL with ccol_iter_next() and runs
the body once for each element. Inside the body you get typed access to
the element through ccol_iter_key_ptr(it) and ccol_iter_val_ptr(it).
 
The iterator is destroyed when the loop ends, whether the loop runs to
the end of the sequence or leaves through a break or a return.

container  A cvec, chmap or cbmap variable.
it         Name for the iterator variable.
body       Compound statement to run for each element. The macro takes
           it as a variadic argument, so a comma inside a nested function
           call is safe.

Do NOT change the container inside the body. An insertion or a deletion
invalidates the iterator and the behavior is undefined.
The macro uses statement expressions and the cleanup attribute, so it
needs GCC or Clang.

chmap_construct(freq, char*, int);
/* ... fill the map ... */
ccol_for_each(freq, it, {
    printf("%-12s %d\n", *ccol_iter_key_ptr(it),
                         *ccol_iter_val_ptr(it));
});
chmap_destroy(freq);

ccol_iter_declare(3), ccol_begin(3), ccol_iter_next(3), ccol_iter_key_ptr(3), ccol_iter_val_ptr(3)