Skip to content

Commit af2bba2

Browse files
authored
Merge pull request #16 from DoctorLai/updates
Refactor views-zip-enumerate
2 parents e45d60e + 626201d commit af2bba2

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

views-zip-enumerate/main.cpp

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
11
#include <iostream>
22
#include <string>
3+
#include <string_view>
4+
#include <functional>
35
#include <ranges>
46

7+
using pair = std::pair<size_t, char>;
8+
9+
void
10+
default_callback(pair p)
11+
{
12+
std::cout << "Index: " << p.first << ", Character: " << p.second << '\n';
13+
}
14+
515
void
6-
enumerate(std::string_view str)
16+
enumerate(std::string_view str, std::function<void(pair)> callback = nullptr)
717
{
818
for (const auto& [index, character] : std::views::zip(std::views::iota(0), str)) {
9-
std::cout << index << ": " << character << '\n';
19+
callback({index, character});
1020
}
1121
}
1222

@@ -15,15 +25,14 @@ main(int argc, char* argv[])
1525
{
1626
if (argc < 2) {
1727
std::cerr << "Usage: " << argv[0] << " <string1> <string2> ...\n";
18-
enumerate("default string");
28+
enumerate("default string", default_callback);
1929
// make pipeline happy
2030
return 0;
2131
}
2232
for (int i = 1; i < argc; ++i) {
2333
std::string_view input = argv[i];
2434
std::cout << "Enumerating string: " << input << '\n';
25-
enumerate(input);
26-
std::cout << "------------------------\n";
35+
enumerate(input, [](pair p) { std::cout << "Index: " << p.first << ", Character: " << p.second << '\n'; });
2736
}
2837
return 0;
2938
}

views-zip-enumerate/tests.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/bin/bash
2+
3+
set -ex
4+
5+
./views-zip-enumerate 1234 ABCD

0 commit comments

Comments
 (0)