dimanche 18 février 2018

Value is not stored in the custom obj.

#include <unordered_map>
#include <vector>
#include <string>
#include <sstream>
#include <set>
#include <algorithm>

using namespace std; 

class Trie {
public:
    unordered_map<char, Trie> children;
    string value;
    bool isWord;
    int frequency;

    Trie(const string &);
    Trie();
    void add(const char c);
    string find(const string &);
    void insert(const string &);
    void  setFrequency();
    int getFrequency (); 
};

then sort is called with a lambda function as

sort(results.begin(), results.end(), 
                [=](Trie a,Trie b)->bool { //(const Trie &a...)didn't work as well
                   if(a.frequency == b.frequency) 
                     return a.value.compare(b.value) <0; 
                   else 
                      return  a.frequency > b.frequency;
                } 
            );

Here is how I set frequency

void Trie::setFrequency() {
this->frequency = this->frequency+1;
}

void Trie::add(char c) {
if (value == "") {

    this->children[c] = Trie(string(1, c));
   //this->setFrequency(); 
}
else
    //this->frequency =this->frequency+1;
    this->children[c] = Trie(value + c);
}



void Trie::insert(const string &word) {
Trie * node = this;
for (int i = 0; i < word.length(); i++) {
    const char c = word[i];
    if (node->children.find(c) == node->children.end()){
        node->add(c);
        node->setFrequency();
    }
    node = &node->children[c];
}
node->isWord = true;
}

However, I got all 0s for the frequency as sort is called with the lambda.

Any ideal/ suggestions ? thank you so much in advance. I have trying to print out the frequency, which it does updated. but no in the lambda function.

Aucun commentaire:

Enregistrer un commentaire