Install using a specialized C ++ object comparator

I have a file, the first line on it is the English alphabet, in random order, after that the names. I have to sort the names according to the specified alphabet. My class looks something like this:

class MyCompare(){
   private:
     static map<char, int> order;
   public:
     MyCompare(string alphabet){
        //loop through the string, assign character to it index in the map
        // order[ alphabet[i] ] = i;
     }
     bool operator()(const string s1, const string s2) {
        //compare every character using compchar, return the result
     }
     bool compchar(const char c1, const char c2){
        return order[c1]<order[c2];
     }        

}

basically, I did something like this:

int i=0;

if (myfile.is_open()) {
    while ( myfile.good() ) {
        i++;
        getline (myfile,line);
        if(i ==1){
            MyCompare st(line);
            set<string, MyCompare> words(st);                
        }
        words.insert(line);             
    }
    myfile.close();
}

Of course, this does not work, because the set is not visible outside the if block. I can’t think of anything else, though ... Please inform.

+3
source share
2 answers

Read the first line, then create your set and enter a loop.

if (myfile.is_open()) {
    getline (myfile,line);
    MyCompare st(line);
    set<string, MyCompare> words(st);
    while (getline(myfile,line)) {
        words.insert(line);
    }
    myfile.close();

    // use words here
}
+5
source

This may not be the answer to your problem, but you should almost never test the stream status bits in loop control. Do you want to:

if (myfile.is_open()) {
    while ( getline (myfile,line) ) {
        i++;
        if(i ==1){
            MyCompare st(line);
            set<string, MyCompare> words(st);                
        }
        words.insert(line);             
    }
    myfile.close();
}
0
source

All Articles