I'm pretty new to C++. This code was provided as an example to use Lambdas to index strings. ie. string "123" becomes unsigned int 123.
My issue is the main for-loop, the line starting with lIndex
. I understand the second half of this line where the number character aKey[i]
is subtracted by '0's ASCII code to produce the ASCII code of the decimal version of the number. However, I can't wrap my head around why lIndex
keeps accumulating and multiplying by ten. Thank you if you answer!
template <typename T, size_t N = 20>
class StringIndexerLambda {
private:
BasicIndexer<T, N> fElements;
public:
T& operator[](const std::string& aKey) { return item(aKey); }
T& item(
const std::string& aKey, std::function<size_t(const std::string&)> aMap = [](const std::string& aKey) {
size_t lIndex = 0;
for (size_t i = 0; i < aKey.size(); i++) {
lIndex = lIndex * 10 + (static_cast<size_t>(aKey[i]) - '0');
}
return lIndex;
}) {
size_t lIndex = aMap(aKey);
assert(lIndex < fElements.size());
return fElements[lIndex];
}
};
Reading "I understand the second half of this line where the number character 'aKey[i]' is subtracted by '0's ASCII code to produce the ASCII code of the decimal version of the number." I kind of doubt that you really understood that, but I will assume that it is more a problem of phrasing than a misunderstanding.
I trust that what you want answered is "why lIndex keeps accumulating and multiplying by ten".
To answer allow me to give some orders to you which, you have to execute, as a human being:
That is easy, the result is 14628. If you got 82641 that is also fine.
Now a variation, which I think will give you the answer you want.
Try to find a solution with the pocket calculator at this point.
Solution:
+0=
(tricky step obeyed)*10+
(get the current number prepared so that the next digit can be used)4
+0=
*10+
Then you effectively get ((((1*10)+4)*10+6)*10+2)*10+8=14628
I mean this to be self-explanatory without any further explanation, because I think what you need is the "Ooooh.... I see" experience from doing yourself what you see in the code.
I recommend pen and paper or pocket calculator experiments/recreations in many cases of hard to understand code.