In this exercise I am using Visual Studio 2019 and a modified version of the std_lib_facilities header found here.
Chapter 20 // Exercise 7
Find the lexicographical last string in an unsorted vector<string>.
This exercise is a "gotcha". Lexicographical order is basically alphabetical order but to computers, uppercase is alphabetically before lowercase so Zebra would come before zany when it should be after.
Since Bjarne goes on about the std library in this chapter I had a poke round the library to see what functions I could use:
- string::compare() does not compare lexicographically.
- strcmp() does not compare lexicographically.
- std::lexicographical_compare() ironically does not compare lexicographically but there is another version that takes a predicate.
Creating a function to do this though was an exercise in Chapter 18 (exercise 3). I'll need to go back and edit that as I didn't stop to think about uppercase and lowercase characters. Bjarne you devious snake.
So instead I created a simple predicate function that you can pass to lexicographical_compare that returns if tolower(char 1) < tolower(char 2). This solves the problem.
No comments:
Post a Comment