sort a vector of strings according to their length c++
To sort a vector of strings according to their length in C++, you can use the std::sort
function along with a custom comparator. Here are the steps to do that:
- Include the necessary headers:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
- Define a custom comparator function to compare the lengths of two strings:
bool compareLength(const std::string& str1, const std::string& str2) {
return str1.length() < str2.length();
}
- Create a vector of strings and populate it with the desired values:
std::vector<std::string> strings = {"apple", "banana", "cherry", "date"};
- Use the
std::sort
function to sort the vector using the custom comparator:
std::sort(strings.begin(), strings.end(), compareLength);
- Print the sorted vector of strings:
for (const auto& str : strings) {
std::cout << str << " ";
}
The output will be: "date apple cherry banana".
That's it! The vector of strings will be sorted in ascending order based on their lengths.