@@ -76,52 +76,6 @@ auto result = std::ranges::find_if(stuff, do_something);
76
76
Note, STL `<algorithm>` library can also use lambdas.
77
77
78
78
79
- **Example**: For a given input, find the appropriate prefix.
80
- ```cpp
81
- constexpr std::array<std::string_view, 5> prefixes {"", "k", "M", "G", "T"};
82
- size_t base = 0;
83
- double inUnits = bytes;
84
- constexpr double siFactor {1000.0};
85
-
86
- while (inUnits > siFactor && base < prefixes.size() - 1) {
87
- ++base;
88
- inUnits /= siFactor;
89
- }
90
-
91
- auto prefix = prefixes[base];
92
- ```
93
-
94
- Let’s make the data more expressive, more self-contained, and use STL
95
- algorithm ` find_if ` :
96
-
97
- ``` cpp
98
- using PrefixSpec = struct {
99
- char prefix;
100
- unsigned long long factor;
101
- };
102
-
103
- static constexpr std::array<PrefixSpec, 7 > sortedPrefixes {
104
- {{'E', 1ULL << 60}, // 1 << 60 = 2^60
105
- {'P', 1ULL << 50},
106
- {'T', 1ULL << 40},
107
- {'G', 1ULL << 30},
108
- {'M', 1ULL << 20}, // 1 << 20 = 2^20 = 1024
109
- {'k', 1ULL << 10}, // 1 << 10 = 2^10 = 1024
110
- {'\0', 0}}};
111
-
112
- const auto res = std::find_if(prefixes.begin(), prefixes.end(), [ &] (const auto& spec) {
113
- return spec.factor <= size;
114
- });
115
-
116
- // Add one digit after the decimal place for all prefixed sizes
117
- return res->factor
118
- ? fmt::format(" {:.1f} {}B" , static_cast <double >(size) / res->factor, res->prefix)
119
- : fmt::format(" {} B" , size);
120
- ```
121
-
122
- Simpler, cleaner, more reliable. No raw loops, magic numbers or calculations.
123
- Note the reverse iterator.
124
-
125
79
## Code comments
126
80
127
81
> Don’t comment bad code—rewrite it.
0 commit comments