2011-05-09 81 views
3

我有一个文件,它的第一行是英文字母,随机顺序,之后,名称。我应该根据给定的字母来排列名字。我的类看起来是这样的:设置自定义函数对象比较器c + +

class MyCompare(){ 
    private: 
    static map<char, int> order; 
    public: 
    MyCompare(string alphabet){ 
     //loop through the string, assign character to it's 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]; 
    }   

}

主,我做了这样的事情:

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(); 
} 
当然

,这是不行的,因为设置ISN”在if块之外可见。我不能拿出任何东西,但... 请指教。

+0

我不知道看这个代码应该做什么。 – 2011-05-09 18:05:15

+0

“操作员”之后应该有一个操作员... – 2011-05-09 18:05:36

+0

@Mike DeSimone对不起,错字。 – adamors 2011-05-09 18:06:39

回答

5

阅读第一行,然后创建你的设置,然后进入循环。

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 
} 
+0

我会建议对这段代码做一个小的修改,以便利用@Mike DeSimone添加到问题中的注释 - 检查if(!myfile.is_open){//处理错误情况},然后检查其余部分代码不需要嵌套。 – pstrjds 2011-05-09 20:11:07

0

可能不是您的问题的答案,但在控制循环时几乎不应该测试流状态位。你想:

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

摘下了http://www.cplusplus.com/doc/tutorial/files/ lol – adamors 2011-05-09 18:07:48

+0

@Ors这解释了很多。在地球上你没有办法从网络资源中学习C++。 – 2011-05-09 18:08:36

+0

就像[学习HTML,CSS等最糟糕的方式是去w3schools.com](http://w3fools.com/)一样,尽管它们在Google上排名很高。 – 2011-05-09 18:22:54