Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare string before inserting into set c++

Tags:

c++

set

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
like image 891
XDProgrammer Avatar asked Dec 11 '22 22:12

XDProgrammer


1 Answers

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.

like image 71
Galik Avatar answered Dec 28 '22 14:12

Galik