Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
stl_utils_example.C
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
153#include <iostream>
154#include <iomanip>
155#include <string>
156#include <vector>
157#include <list>
158#include <set>
159#include <algorithm>
160#include <numeric>
161
162#include <ah-stl-utils.H>
163#include <htlist.H>
164#include <tpl_dynArray.H>
165
166using namespace std;
167using namespace Aleph;
168
169// ============================================================================
170// Helper functions
171// ============================================================================
172
173void print_header(const string& title)
174{
175 cout << "\n";
176 cout << "+" << string(70, '-') << "+" << endl;
177 cout << "| " << left << setw(68) << title << " |" << endl;
178 cout << "+" << string(70, '-') << "+" << endl;
179}
180
181void print_subheader(const string& subtitle)
182{
183 cout << "\n " << subtitle << endl;
184 cout << " " << string(subtitle.length(), '-') << endl;
185}
186
187template <typename Container>
188void print_stl_container(const string& name, const Container& c)
189{
190 cout << " " << name << " (" << c.size() << " elements): ";
191 for (const auto& item : c)
192 cout << item << " ";
193 cout << endl;
194}
195
196template <typename T>
197void print_dynlist(const string& name, const DynList<T>& l)
198{
199 cout << " " << name << " (" << l.size() << " elements): ";
200 for (auto it = l.get_it(); it.has_curr(); it.next_ne())
201 cout << it.get_curr() << " ";
202 cout << endl;
203}
204
205template <typename T>
206void print_dynarray(const string& name, const DynArray<T>& arr)
207{
208 cout << " " << name << " (" << arr.size() << " elements): ";
209 for (size_t i = 0; i < arr.size(); ++i)
210 cout << arr(i) << " ";
211 cout << endl;
212}
213
214// ============================================================================
215// Example 1: Vector <-> DynList conversions
216// ============================================================================
217
219{
220 print_header("Example 1: std::vector <-> DynList Conversions");
221
222 // Colombian cities
224 "Bogota", "Medellin", "Cali", "Barranquilla", "Cartagena"
225 };
226
227 print_subheader("STL vector to Aleph-w DynList");
228 print_stl_container("Original vector", cities_vec);
229
230 // Convert to DynList
232 print_dynlist("Converted DynList", cities_list);
233
234 // Also works with vector_to_DynList
236 cout << " (vector_to_DynList also works)" << endl;
237
238 print_subheader("Aleph-w DynList to STL vector");
239
240 // Add more cities to DynList
241 cities_list.append("Santa Marta");
242 cities_list.append("Bucaramanga");
243
244 // Convert back to vector
246 print_stl_container("Converted vector", cities_vec2);
247
248 print_subheader("Numeric example");
249
250 // Population data (thousands)
251 vector<int> population = {8281, 2569, 2228, 1274, 1047};
252 print_stl_container("Population vector", population);
253
254 DynList<int> pop_list = to_DynList(population);
255 print_dynlist("Population DynList", pop_list);
256
257 // Sum using DynList's fold
258 int total = pop_list.foldl(0, [](int acc, int p) { return acc + p; });
259 cout << " Total population: " << total << " thousand" << endl;
260}
261
262// ============================================================================
263// Example 2: Vector <-> DynArray conversions
264// ============================================================================
265
267{
268 print_header("Example 2: std::vector <-> DynArray Conversions");
269
270 // Colombian department areas (km²)
271 vector<double> areas = {63612, 23188, 22140, 44640, 25020, 24885};
272
273 print_subheader("STL vector to Aleph-w DynArray");
274 print_stl_container("Areas vector", areas);
275
277 print_dynarray("Areas DynArray", areas_arr);
278
279 print_subheader("Aleph-w DynArray to STL vector");
280
281 // Modify DynArray
282 areas_arr.append(30000.5);
283 areas_arr.append(55000.0);
284
285 vector<double> areas_vec2 = DynArray_to_vector(areas_arr);
286 print_stl_container("Modified areas vector", areas_vec2);
287
288 // Calculate statistics using STL algorithms
289 double total = accumulate(areas_vec2.begin(), areas_vec2.end(), 0.0);
290 double avg = total / areas_vec2.size();
291
292 cout << "\n Statistics (using STL algorithms):" << endl;
293 cout << " Total area: " << fixed << setprecision(1) << total << " km2" << endl;
294 cout << " Average: " << avg << " km2" << endl;
295}
296
297// ============================================================================
298// Example 3: std::list <-> DynList conversions
299// ============================================================================
300
302{
303 print_header("Example 3: std::list <-> DynList Conversions");
304
305 // Colombian rivers
307 "Magdalena", "Cauca", "Atrato", "Meta", "Guaviare", "Caqueta"
308 };
309
310 print_subheader("std::list to DynList");
311 print_stl_container("Rivers std::list", rivers_stl);
312
314 print_dynlist("Rivers DynList", rivers_aleph);
315
316 print_subheader("DynList to std::list");
317
318 // Add more rivers
319 rivers_aleph.append("Putumayo");
320 rivers_aleph.append("Orinoco");
321
323 print_stl_container("Extended rivers std::list", rivers_stl2);
324
325 print_subheader("Using stl_container_to_dynList (generic)");
326
327 // Works with any STL container
328 set<int> altitude_set = {2640, 1538, 995, 18, 5, 213, 965};
330 print_dynlist("Altitudes from set", altitude_list);
331 cout << " (Note: set maintains sorted order)" << endl;
332}
333
334// ============================================================================
335// Example 4: Iterator range conversions
336// ============================================================================
337
339{
340 print_header("Example 4: Iterator Range Conversions");
341
342 // Temperature readings
343 vector<double> temps = {23.5, 25.1, 24.8, 26.2, 22.9, 27.0, 25.5, 24.0};
344
345 print_subheader("Full range to DynList");
346 print_stl_container("Temperatures", temps);
347
349 print_dynlist("All temps DynList", all_temps);
350
351 print_subheader("Partial range to DynList");
352
353 // First 4 readings
355 print_dynlist("First 4 temps", first_temps);
356
357 // Last 3 readings
359 print_dynlist("Last 3 temps", last_temps);
360
361 print_subheader("From raw array");
362
363 int days[] = {1, 2, 3, 4, 5, 6, 7};
365 print_dynlist("Days from array", days_list);
366}
367
368// ============================================================================
369// Example 5: Tuple conversions
370// ============================================================================
371
373{
374 print_header("Example 5: Tuple Conversions");
375
376 print_subheader("Homogeneous tuple to DynList");
377
378 // Coffee production by region (tons)
379 auto production = make_tuple(125000, 98000, 85000, 72000, 65000);
380
381 cout << " Tuple elements: ";
382 tuple_for_each(production, [](int val) {
383 cout << val << " ";
384 });
385 cout << endl;
386
388 print_dynlist("Production DynList", prod_list);
389
390 print_subheader("Tuple to Array");
391
392 auto regions = make_tuple(string("Huila"), string("Narino"),
393 string("Cauca"), string("Tolima"));
394
395 cout << " Tuple elements: ";
396 tuple_for_each(regions, [](const string& s) {
397 cout << s << " ";
398 });
399 cout << endl;
400
402 cout << " Regions Array (" << regions_arr.size() << " elements): ";
403 for (auto it = regions_arr.get_it(); it.has_curr(); it.next_ne())
404 cout << it.get_curr() << " ";
405 cout << endl;
406
407 print_subheader("tuple_for_each for heterogeneous tuples");
408
409 auto mixed = make_tuple(42, 3.14159, string("Colombia"), 'C');
410
411 cout << " Processing heterogeneous tuple:" << endl;
412 tuple_for_each(mixed, [](const auto& val) {
413 cout << " -> " << val << endl;
414 });
415}
416
417// ============================================================================
418// Example 6: Variadic argument packing
419// ============================================================================
420
422{
423 print_header("Example 6: Variadic Argument Packing");
424
425 print_subheader("variadic_to_vector");
426
427 // Create vector from arguments
428 vector<int> scores = variadic_to_vector<int>(95, 87, 92, 78, 88, 91);
429 print_stl_container("Scores vector", scores);
430
431 // With doubles
432 vector<double> rates = variadic_to_vector<double>(4.5, 3.8, 4.2, 4.0);
433 print_stl_container("Rates vector", rates);
434
435 print_subheader("variadic_to_DynList");
436
438 "Cafe", "Flores", "Banano", "Carbon", "Petroleo"
439 );
440 print_dynlist("Products DynList", products);
441
442 print_subheader("Practical use case");
443
444 // Build a quick list for processing
446 "Leticia", "Mitú", "Puerto Inírida", "San José del Guaviare"
447 );
448
449 cout << " Amazon region cities:" << endl;
450 for (auto it = cities.get_it(); it.has_curr(); it.next_ne())
451 cout << " - " << it.get_curr() << endl;
452}
453
454// ============================================================================
455// Example 7: Map transformations
456// ============================================================================
457
459{
460 print_header("Example 7: Map Transformations");
461
462 print_subheader("map_vector: Transform elements");
463
464 // GDP per capita in USD
465 vector<double> gdp = {6500, 8200, 7800, 5900, 12000};
466 print_stl_container("GDP per capita (USD)", gdp);
467
468 // Convert to COP (1 USD = 4150 COP)
469 auto gdp_cop = map_vector(gdp, [](double usd) { return usd * 4150.0; });
470
471 cout << " GDP per capita (COP): ";
472 for (const auto& v : gdp_cop)
473 cout << fixed << setprecision(0) << v << " ";
474 cout << endl;
475
476 print_subheader("map_vector: Type transformation");
477
478 // Convert to formatted strings
479 auto gdp_strings = map_vector(gdp, [](double val) {
480 return "$" + to_string(static_cast<int>(val)) + " USD";
481 });
482 print_stl_container("GDP strings", gdp_strings);
483
484 print_subheader("Chained transformations");
485
486 vector<int> quantities = {10, 25, 15, 30, 20};
487 print_stl_container("Quantities", quantities);
488
489 // Apply discount and convert to DynList
490 auto with_discount = map_vector(quantities, [](int q) {
491 return q * 0.9;
492 });
493
495 print_dynlist("After 10% discount", final_list);
496}
497
498// ============================================================================
499// Example 8: Integration example
500// ============================================================================
501
503{
504 print_header("Example 8: Integration - Processing Pipeline");
505
506 cout << "\n Scenario: Process sales data from STL to Aleph-w and back\n" << endl;
507
508 // Step 1: Start with STL data
510 {"Bogota", 1250000},
511 {"Medellin", 890000},
512 {"Cali", 720000},
513 {"Barranquilla", 450000},
514 {"Cartagena", 380000}
515 };
516
517 cout << " Step 1: Original STL data (city, sales)" << endl;
518 for (const auto& [city, amount] : sales)
519 cout << " " << left << setw(15) << city << fixed << setprecision(0)
520 << amount << " COP" << endl;
521
522 // Step 2: Extract cities and amounts separately
524 vector<double> amounts;
525 for (const auto& [city, amount] : sales) {
526 cities.push_back(city);
527 amounts.push_back(amount);
528 }
529
530 // Step 3: Convert to Aleph-w for processing
533
534 cout << "\n Step 2: Converted to Aleph-w DynList" << endl;
535 cout << " Cities: " << cities_list.size() << " items" << endl;
536 cout << " Amounts: " << amounts_list.size() << " items" << endl;
537
538 // Step 4: Process with Aleph-w functional operations
539 double total = amounts_list.foldl(0.0, [](double acc, double v) {
540 return acc + v;
541 });
542
543 double avg = total / amounts_list.size();
544
545 auto above_avg = amounts_list.filter([avg](double v) {
546 return v > avg;
547 });
548
549 cout << "\n Step 3: Aleph-w processing" << endl;
550 cout << " Total sales: " << fixed << setprecision(0) << total << " COP" << endl;
551 cout << " Average: " << avg << " COP" << endl;
552 cout << " Cities above average: " << above_avg.size() << endl;
553
554 // Step 5: Convert back to STL for output
555 vector<double> above_vec = to_vector(above_avg);
556
557 cout << "\n Step 4: Back to STL for output" << endl;
558 cout << " Sales above average: ";
559 for (double v : above_vec)
560 cout << v << " ";
561 cout << endl;
562}
563
564// ============================================================================
565// Main
566// ============================================================================
567
568int main()
569{
570 cout << "\n";
571 cout << "========================================================================" << endl;
572 cout << " ALEPH-W STL UTILS EXAMPLE" << endl;
573 cout << " STL <-> Aleph-w Container Conversions" << endl;
574 cout << "========================================================================" << endl;
575
584
585 cout << "\n";
586 cout << "========================================================================" << endl;
587 cout << " Example completed successfully!" << endl;
588 cout << "========================================================================" << endl;
589 cout << endl;
590
591 return 0;
592}
593
Conversion utilities between Aleph-w containers and STL containers.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:138
size_t size() const noexcept
Return the current dimension of array.
Dynamic singly linked list with functional programming support.
Definition htlist.H:1423
T & append(const T &item)
Append a new item by copy.
Definition htlist.H:1562
size_t size() const noexcept
Count the number of elements of the list.
Definition htlist.H:1319
__T foldl(const __T &init, Op &op) const
Fold the elements of the container to a specific result.
Definition ah-dry.H:1034
Aleph::DynList< T > filter(Operation &operation) const
Filter the elements of a container according to a matching criteria.
Definition ah-dry.H:1135
size_t length() const noexcept
Count the number of elements of a container.
Definition ah-dry.H:1385
auto get_it() const
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:190
iterator end() noexcept
Return an STL-compatible end iterator.
iterator begin() noexcept
Return an STL-compatible iterator to the first element.
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
Definition ah-arena.H:89
Array< T > tuple_to_array(const std::tuple< T, U... > &t)
Convert a tuple to an Array.
auto range_to_DynList(Iterator begin, Iterator end) -> DynList< std::decay_t< decltype(*begin)> >
Convert an iterator range to a DynList.
DynList< T > to_DynList(const Array< T > &a)
Convert an Array to a DynList.
Definition ah-convert.H:147
DynList< T > list_to_DynList(const std::list< T > &l)
Convert a std::list to a DynList.
T accumulate(Itor beg, Itor end, T initValue)
Accumulate values in a range.
Definition ahAlgo.H:1493
DynList< T > vector_to_DynList(const std::vector< T > &v)
Convert a std::vector to a DynList.
Definition ah-convert.H:250
DynList< T > tuple_to_dynlist(const std::tuple< T, U... > &t)
Convert a tuple to a DynList.
auto stl_container_to_dynList(const StlContainer &container) -> DynList< typename StlContainer::value_type >
Convert any STL container to a DynList.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
DynArray< T > vector_to_DynArray(const std::vector< T > &v)
Convert a std::vector to a DynArray.
Definition ah-convert.H:291
std::vector< T > DynArray_to_vector(const DynArray< T > &arr)
Convert a DynArray to a std::vector.
std::list< T > DynList_to_list(const DynList< T > &l)
Convert a DynList to a std::list.
void tuple_for_each(const std::tuple< Ts... > &tuple, F func, std::index_sequence< Is... >)
Apply a function to each element in a tuple (tuple first).
std::vector< typename C::Item_Type > to_vector(const C &c)
Convert a container to a std::vector.
Definition ah-convert.H:228
DynList< T > maps(const C &c, Op op)
Classic map operation.
auto map_vector(const std::vector< T > &v, Op op) -> std::vector< std::decay_t< decltype(op(v[0]))> >
Map a function over a std::vector.
STL namespace.
void print_header()
void demo_vector_dynlist()
void demo_range_conversions()
void demo_integration()
void print_dynlist(const string &name, const DynList< T > &l)
void demo_variadic_packing()
void demo_list_dynlist()
void print_dynarray(const string &name, const DynArray< T > &arr)
void demo_tuple_conversions()
void demo_map_transformations()
void print_subheader(const string &subtitle)
void demo_vector_dynarray()
int main()
void print_stl_container(const string &name, const Container &c)
Lazy and scalable dynamic array implementation.
DynList< int > l