sort strings by length and by alphabet
To sort strings by length and alphabet in C++, you can follow these steps:
Include the necessary header files:
cpp #include <iostream> #include <algorithm> #include <vector> #include <string>
Define a custom comparison function to sort strings by length:
cpp bool compareByLength(const std::string &a, const std::string &b) { return a.length() < b.length(); }
Define a custom comparison function to sort strings alphabetically:
cpp bool compareAlphabetically(const std::string &a, const std::string &b) { return a < b; }
Create a vector of strings:
cpp std::vector<std::string> strings = {"apple", "banana", "orange", "grape", "pear"};
Sort the strings by length using the custom comparison function:
cpp std::sort(strings.begin(), strings.end(), compareByLength);
Display the sorted strings by length:
cpp std::cout << "Sorted by length:" << std::endl; for (const auto &str : strings) { std::cout << str << std::endl; }
Sort the strings alphabetically:
cpp std::sort(strings.begin(), strings.end(), compareAlphabetically);
Display the strings sorted alphabetically:
cpp std::cout << "Sorted alphabetically:" << std::endl; for (const auto &str : strings) { std::cout << str << std::endl; }
Output the sorted strings by length and alphabet:
Sorted by length: pear grape apple banana orange Sorted alphabetically: apple banana grape orange pear