gpt4 book ai didi

c++ - 将 C++ 分配给映射迭代器时出现类型错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:43:49 27 4
gpt4 key购买 nike

我正在尝试从 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();

完整的代码 list :

#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;
}

最佳答案

您需要 it->second,不带括号。 secondstd::pair 的数据成员, 不是成员函数。

const Rule_collection& c = it->second;

关于c++ - 将 C++ 分配给映射迭代器时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19927690/

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