gpt4 book ai didi

c++ - 使用自定义函数对象比较器 C++ 设置

转载 作者:太空狗 更新时间:2023-10-29 20:47:21 25 4
gpt4 key购买 nike

我有一个文件,第一行是英文字母,顺序是随机的,然后是名字。我应该根据给定的字母表对名称进行排序。我的类(class)看起来像这样:

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

当然,这是行不通的,因为集合在 if block 之外是不可见的。不过,我想不出其他任何东西......请指教。

最佳答案

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

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
}

关于c++ - 使用自定义函数对象比较器 C++ 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5940690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com