You can buy my book directly here: http://mng.bz/AdAQ - or just go look at the table of contents. You can also buy it from Amazon: https://amzn.to/4dMJ0aG
gives the answer vectorch.
Using a map still helps us learn some new features. Many operations use a std::pair<const Key, T>, which can mean your code has
for (const auto & [key, value] : dictionary)
We can bind to std::tuple and more besides. We can bind to arrays and even a structure’s non-static members too. For example, given
struct DataObject { int x{ 0 }; double y{ 1.23 }; };
we can write
DataObject data {};
auto [x, y] = data;
It is the programmer's responsibility to ensure that std::string_view does not outlive the pointed-to character array
The chapter also includes a brief overview of big-O (order) notation, to help us think through potential inefficiencies, and this helps as a basis for unordered (hash based) lookup table in the next chapter.
We also use a std::multimap, to allow duplicate values per key. This allows us to load a dictionary from a file. There are several free dictionaries on the internet. Take your pick, but be warned my book only handles ASCII - other character sets would need a whole book, or at least a dedicated chapter or two! Loading a file doesn't need much work, once you've got the hang of streams. An input file stream is called std::ifstream, We can open a file, using its name, which may need to be fully pathed:
std::ifstream infile{ filename };
and use the stream in a Boolean context to see whether it is open:
if (infile)
// all good
The stream closes as it goes out of scope, which is sensible.- If we use operator[] for a std::map, say dictionary["word"], what are the two things that might happen?
- Can you remember how to find all the values for a given key in a std::multimap? (Clue: look up lower and upper bound)
- Have a go at finding words that can overlap a given word. (Maybe find a free dictionary so you can look up the words, and pick one at random to start with).
No comments:
Post a Comment