>>6524
In Modern C++ (17 or greater), an
if() logical test can have two sections; the initializer, and the conditional. This is similar to the way a
for() loop works. If you read the *****preference.com link to map::find() posted above, then you saw that an
iterator is the return type from the find() function. Iterators are kind of like C-pointers for C++, and you use similar syntax for dereferencing them for example.
Further, a std::map item has two named parts, 'first' and 'second'. First is the key, and second is the value.
Combining all these facts together, and we can write a search test to see if the
say_num parameter was actually found within our map:
std::string say(uint32_t say_num) const {
if (auto search = sayings.find(say_num); search != sayings.end())
return search->second;
}
This is saying to the system, "Look for this key number. If you find it in the std::map, return true". This is the correct behavior we're looking for ofc.
Re-running our system now shows us that, sure enough, we're back to green.
> #1
Great! We're done right? Well wait, what's this yellow squiggle and warning message?
> #2
Apparently our function has a problem still. Turns out we're only handling behavior for the valid case. What happens if we pass an
invalid number into waifu.say() ? For example, since we currently have only 4 sayings in our map (numbered 1 - 4), what happens if we 'inadvertently' pass in a number not in that range?
REQUIRE(waifu.say(9'001) == "Foobar9000");
> #3
The failing test shows us what our new say() code does with an invalid input key number:
with expansion:
"" == "Foobar9000"
Similar to earlier in our code, the function just returns an empty string. Instead of simply returning
nothing from our function with an invalid input, what if we improved it a little by at least indicating that our waifu doesn't understand the saying number we asked for from her.
std::string say(uint32_t say_num) const {
if (auto search = sayings.find(say_num); search != sayings.end())
return search->second;
return "I don't understand Oniichan...";
}
Ah, that got rid of the squiggles too. Now our waifu is telling us if she doesn't understand what we just asked for.
> #4
But we're still failing that final test. Sometimes the
tests themselves are the problem. Let's change the invalid, bogus one to use the
!= operator instead and re-run:
REQUIRE(waifu.say(9'001) != "Foobar9000");
> #5
So, seems like we're back to all green and we have a system that will properly look up a valid key and return the correct text to us, and provide a helpful message when we pass in an invalid one (and not break the system). Seems like we're making good progress with our Robowaifu class so far and our tests.