C++ std::string::compare
Check the ordering of two ASCII shelf labels before inserting one into a sorted display.
A simple example
std::string::compare
- Start with "a" and "b"
- Do this Compare their order
- Result a comes first
Syntax
value.compare(other) < 0
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonOrder two shelf areas
A directory orders shelf or room labels as text. Compare their spelling under the chosen ordering rule and check what happens when a label contains digits that look like a number.
#include <iostream>
#include <string>
int main() {
const std::string value = "A-10";
const std::string other = "B-10";
std::cout << ((value.compare(other) < 0) ? "yes" : "no") << "\n";
return 0;
}
yes
The first different letter places A before B.
Recognize tied course codes
A directory orders short labels entered using different capitalization. Decide when two entries should compare as a tie and when the comparison should place one label first.
#include <iostream>
#include <string>
int main() {
const std::string value = "BIO";
const std::string other = "BIO";
std::cout << ((value.compare(other) < 0) ? "yes" : "no") << "\n";
return 0;
}
no
Equal codes do not precede each other.
Sort art studio lockers
A school uses two-letter locker prefixes. The catalog compares the two ASCII codes in text order. Which code sorts first?
What to watch for
These examples assume ASCII shelf labels. Human names may require locale-aware collation.