我有一个文件,它的第一行是英文字母,按随机顺序,然后是名字.我应该根据给出的字母对名称进行排序.我的班级看起来像这样:
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];
}
Run Code Online (Sandbox Code Playgroud)
}
在主要方面,我做了这样的事情:
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();
}
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用,因为在if块之外看不到集合.我不能拿出别的东西,但是......请指教.
阅读第一行,然后创建你的设置,然后进入循环.
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
}
Run Code Online (Sandbox Code Playgroud)