Im trying to compare string before inserting to my set by comparing the length of the string. The shortest string should be inserted first. I dont know whats going on but some of the words are not on the set.
My code:
#include <iostream>
#include <string>
#include <set>
struct compare {
bool operator() (const string& a, const string& b) const{
return a.size() < b.size();
}
};
template<typename T>
void print(const T& t){
for(auto& it : t)
cout << it << endl;
}
int main() {
string word;
set<string, compare> c;
while(cin >> word)
c.insert(word);
print(c);
return 0;
}
Here are the test words to be inserted
Apple
Apricots
Avocado
Durian
Fig
Tangerine/Clementine
Kumquat
Lemon
Pear
Prunes
Raspberries
Strawberries
Watermelon
and here is the OUTPUT
Fig
Pear
Apple
Durian
Avocado
Apricots
Watermelon
Raspberries
Strawberries
Tangerine/Clementine
It works as expected, but apparently some words are missing like:
Kumquat
Lemon
Prunes
A std::set can not contain duplicates. In this case it can't have two strings the same length. Perhaps you would do better using a std::multiset?
#include <iostream>
#include <string>
#include <set>
struct compare {
bool operator() (const std::string& a, const std::string& b) const{
return a.size() < b.size();
}
};
template<typename T>
void print(const T& t){
for(auto& it : t)
std::cout << it << std::endl;
}
int main() {
std::string word;
std::multiset<std::string, compare> c; // multiset!!!
while(std::cin >> word)
c.insert(word);
print(c);
return 0;
}
Output:
Fig
Pear
Apple
Lemon
Durian
Prunes
Avocado
Kumquat
Apricots
Watermelon
Raspberries
Strawberries
Tangerine/Clementine
NOTE: This solution allows duplicate string lengths so that strings can be sorted by length. But that means it also allows duplicate string values so that the very same string can appear more than once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With