2012-07-30 34 views
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
for (set<string>::iterator p = words.begin(); p != words.end(); ++p) 
2

尝试p != words.end();代替。

+2

一个集合不是一个向量,它的迭代器不是指针。 – JRG 2012-07-30 02:57:49

+0

啊...你说得对。不知道为什么我认为矢量。我从我的答案中删除了该笔记。 – pyrospade 2012-07-30 03:43:49