#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
/**
* Finds the largest and smallest words in a given string.
*
* @param text The input string containing words.
* @return A std::pair containing (largest_word, smallest_word).
*/
std::pair<std::string, std::string> findLargestAndSmallestWords(const std::string& text) {
if (text.empty()) {
return {"", ""};
}
// Split the string into words using std::stringstream (similar to Go's strings.Fields)
std::stringstream ss(text);
std::vector<std::string> words;
std::string word;
while (ss >> word) {
words.push_back(word);
}
if (words.empty()) {
return {"", ""};
}
// Use std::max_element and std::min_element with a custom length-comparison lambda
auto largestIt = std::max_element(words.begin(), words.end(),
[](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
auto smallestIt = std::min_element(words.begin(), words.end(),
[](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
return {*largestIt, *smallestIt};
}
int main() {
std::string s = "C++ is a powerful general-purpose programming language";
// Use C++17 structured bindings to destructure the returned std::pair cleanly
auto [largest, smallest] = findLargestAndSmallestWords(s);
std::cout << "Largest word: " << largest << '\n';
std::cout << "Smallest word: " << smallest << '\n';
}
/*
run:
Largest word: general-purpose
Smallest word: a
*/