0

我正在尝试从 Accelerated C++ 一书中学习 C++。当尝试编译下面的代码时,我认为它是书中代码的精确副本,我收到以下错误,我不明白为什么。另外,我不知道如何调试此错误。任何指向该方向的指针(用于快速调试此类错误的问题解决策略)将不胜感激。提前致谢!这是编译器错误:

g++ main.cpp split.cpp -o main
main.cpp: In function ‘void gen_aux(const Grammar&, const string&, std::vector<std::basic_string<char> >&)’:
main.cpp:64:41: error: no match for call to ‘(const std::vector<std::vector<std::basic_string<char> > >) ()’
make: *** [all] Error 1

发生错误的行如下:

const Rule_collection& c = it->second();

完整的代码清单:

#include <cstdlib>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include "split.h"

using std::cin;
using std::cout;
using std::domain_error;
using std::endl;
using std::istream;
using std::logic_error;
using std::map;
using std::pair;
using std::string;
using std::vector;

typedef vector<string> Rule;
typedef vector<Rule> Rule_collection;
typedef map<string, Rule_collection> Grammar;   

int nrand(int n) {
    if (n <= 0 || n > RAND_MAX) {
        throw domain_error("Argument to nrand is out of range");
    }
    const int bucket_size = RAND_MAX / n;
    int r;
    do {
        r = rand() / bucket_size;
    } while (r >= n);

    return r;
}

bool bracketed(const string& s) {
    return s.length() > 0 && s[0] == '<' && s[s.length() - 1] == '>';
}

Grammar read_grammar(istream& in) {
    Grammar g;
    string line;
    while (getline(in, line)) {
        vector<string> words = split(line);
        if (!words.empty()){
            g[words[0]].push_back(Rule(words.begin() + 1, words.end()));
        } 
    }
    return g;
}

void gen_aux(const Grammar& g, const string& word, vector<string>& ret) {
    if (!bracketed(word)) {
        ret.push_back(word);
    }
    else {
        Grammar::const_iterator it = g.find(word);
        if (it == g.end()) {
            throw logic_error("empty rule");
        }
        const Rule_collection& c = it->second();
        const Rule& r = c[nrand(c.size())];
        for (Rule::const_iterator i = r.begin(); i != r.end(); i++) {
            gen_aux(g, *i, ret);
        }
    }
}

vector<string> gen_sentence(const Grammar& g) {
    vector<string> s;
    gen_aux(g, "<sentence>", s);
    return s;
}

int main() {
    vector<string> sentence = gen_sentence(read_grammar(cin));
    if (!sentence.empty()) {
        vector<string>::const_iterator it = sentence.begin();
        cout << *it;
        it++;
        while (it != sentence.end()) {
            cout << " " << *it;
            it++;
        }
        cout << endl;
    }
    return 0;
}
4

2 回答 2

5

你需要it->second,没有括号。second是 的数据成员std::pair,而不是成员函数。

const Rule_collection& c = it->second;
于 2013-11-12T11:20:13.493 回答
1

我想这必须是“const Rule_collection& c = it->second;” 否则,您会尝试像调用函数一样调用向量。

于 2013-11-12T11:24:15.367 回答