1

我正在编写一个程序,它从文件“bible.txt”中读取圣经的所有行。然后它将每一行处理成单独的单词,并将每个单词存储在一个集合和一个多集合中。然后它会找出哪些词被使用了 800 到 1000 次,并将这些词存储在一个向量中。但是,当我尝试创建一个插入器来遍历这组单词时,我收到了错误:

word_count.cpp: In function ‘void sort_words()’:
word_count.cpp:93:62: error: no match for ‘operator<’ in ‘p < words.std::set<_Key,
 _Compare, _Alloc>::end [with _Key = std::basic_string<char>, _Compare = std::less<std::basic_string<char> >, _
Alloc = std::allocator<std::basic_string<char> >, std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<std::basic_string<char> >]()’

这是它有问题的行:

for (set<string>::iterator p = words.begin(); p < words.end(); ++p)

这是完整的代码:

#include <iostream>
#include <string>
#include <fstream>
#include <set>
#include <algorithm>
#include <vector>

using namespace std;

class wordWithCount {

public: 

string word;
int count; 

wordWithCount(string w, int c) : word(w), count(c){} 

bool operator<(const wordWithCount& right) const { 
    if (count != right.count) return count < right.count; 
    return word < right.word; 
} 
};

set<string> words;
multiset<string> multiwords;
vector<string> lines;
vector<wordWithCount> selectedWords;

void readLines(char *filename)

{


string line;
    ifstream infile;
    infile.open(filename);
    if (!infile)
    {
        cerr << filename << " cannot open";
        return;
    }
    getline(infile, line);
    while (!infile.eof())
    {
        lines.push_back(line);
        getline(infile, line);
    }
    infile.close();
}


void process_string (vector<string> lines) {

for (int i = 0; i < lines.size(); i++) {
string line = lines[i];

int found = line.find_first_not_of(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");

while (found != string::npos)
{
    string word = line.substr(0, found);
    if (word.length() > 0)
    {
    words.insert(word);
    multiwords.insert(word);
    }
    line = line.substr(found + 1);
    found = line.find_first_not_of(
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
}
}
}

void sort_words() {
int low = 800;
int high = 1000;

for (set<string>::iterator p = words.begin(); p < words.end(); ++p)
{
    int count = multiwords.count(*p);
    if (count >= low && count <= high)
        selectedWords.push_back(wordWithCount(*p, count));
}
sort(selectedWords.begin(), selectedWords.end());
}

void print_words() {
    for (int i = 0; i < selectedWords.size(); i++)
    {
        cout << selectedWords[i].word << "\t" << selectedWords[i].count;
    }
}

int main() {
    readLines("bible.txt");
    process_string(lines);
    sort_words();
    print_words();

    return 0;
}
4

2 回答 2

4
for (set<string>::iterator p = words.begin(); p != words.end(); ++p)
于 2012-07-30T02:38:55.593 回答
2

试试p != words.end();吧。

于 2012-07-30T02:39:22.243 回答