簡體   English   中英

嘗試在for循環中使用set迭代器時,“ operator <”不匹配

[英]No match for 'operator<' when trying to use set iterator in for loop

我正在編寫一個程序,該程序從文件“ bible.txt”中讀取聖經的所有行。 然后,將每行處理為單個單詞,並將每個單詞存儲在一個集合和一個多集合中。 然后,它發現使用了800至1000次的單詞,並將這些單詞存儲在向量中。 但是,當我嘗試創建一個interator來遍歷這組單詞時,收到錯誤消息:

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;
}
for (set<string>::iterator p = words.begin(); p != words.end(); ++p)

嘗試p != words.end(); 代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM