From d122c77b5a755cd5b3211c26346a84bb2b27cdce Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Thu, 21 Apr 2022 13:47:54 +0200 Subject: Switched to use i_key as primary template type parameter for all containers. Only maps will actually use i_val. Users can still specify i_val for non-maps, so there are no usability changes, other than the option to use i_key always, which makes the implementation and switching between container types simpler. --- examples/city.c | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 examples/city.c (limited to 'examples') diff --git a/examples/city.c b/examples/city.c new file mode 100644 index 00000000..16c9b6f1 --- /dev/null +++ b/examples/city.c @@ -0,0 +1,75 @@ +#include + +typedef struct +{ + cstr name; + cstr country; + float lat, lon; + int population; +} City; + +static inline int City_cmp(const City* a, const City* b) { + int c = cstr_cmp(&a->name, &b->name); + return c ? c : cstr_cmp(&a->country, &b->country); +} + +static inline City City_clone(City c) { + c.name = cstr_clone(c.name); + c.country = cstr_clone(c.country); + return c; +} + +static inline void City_drop(City* c) { + printf("drop %s\n", cstr_str(&c->name)); + c_drop(cstr, &c->name, &c->country); +} + +#define i_type CityArc +#define i_val_bind City +//#include +#include + +#define i_type Cities +#define i_val_arcbox CityArc +#include + +#define i_type CityMap +#define i_key int +#define i_val_arcbox CityArc +#include + + +int main(void) +{ + c_auto (Cities, cities, copy) + c_auto (CityMap, map) + { + struct City_s { const char *name, *country; float lat, lon; int pop; }; + + c_apply(c, Cities_push(&cities, CityArc_from((City){cstr_from(c.name), cstr_from(c.country), + c.lat, c.lon, c.pop})), struct City_s, { + {"New York", "US", 4.3, 23.2, 9000000}, + {"Paris", "France", 4.3, 23.2, 9000000}, + {"Berlin", "Germany", 4.3, 23.2, 9000000}, + {"London", "UK", 4.3, 23.2, 9000000}, + }); + + copy = Cities_clone(cities); // share each element! + + int k = 0, id[] = {8, 4, 3, 9, 2, 5}; + c_foreach (i, Cities, cities) + CityMap_insert(&map, id[k++], CityArc_clone(*i.ref)); + + Cities_pop(&cities); + Cities_pop(&cities); + + printf("Vec:\n"); + c_foreach (c, Cities, cities) + printf("city:%s, %d, use:%ld\n", cstr_str(&c.ref->get->name), c.ref->get->population, CityArc_use_count(*c.ref)); + + printf("\nMap:\n"); + c_forpair (id, city, CityMap, map) + printf("id:%d, city:%s, %d, use:%ld\n", _.id, cstr_str(&_.city.get->name), _.city.get->population, CityArc_use_count(_.city)); + puts(""); + } +} -- cgit v1.2.3