5

在我向你们寻求帮助之前,我已经花了一个多小时研究这个问题。我正在使用 Visual Studio 2012,我刚刚安装了更新 2。

我有这个构造函数

Lexer::Lexer(istream &source1, ostream& listing1)
:source(source1), listing(listing1)
{
vector<string> tempVec = { 
    "and", "begin", "boolean", "break", "call", "end", "else", "false", "halt",
        "if", "input", "integer", "is", "loop", "not", "null", "newline", "or", "output", "procedure"
        "return", "then", "true", "var"
};




tokenToStringVector = tempVec;

for (int k= 0; k < tokenToStringVector.size(); k++)
{
    string key = tokenToStringVector[k];
    lexemeToTokenMap[key] = Token(k); // Function-style type cast
}
}

我的教授写了标题,我写了代码。我收到了这个我无法弄清楚的错误:

1>c:\users\sam\dropbox\compiler project\lexical analyzer\lexer.cpp(8): error C2552: 'tempVec' : non-aggregates cannot be initialized with initializer list
1>          'std::vector<_Ty>' : Types with a base are not aggregate
1>          with
1>          [
1>              _Ty=std::string
1>          ]

我不明白为什么它不会让我这样初始化它。我可以创建一个数组,然后创建一个循环来添加到向量中,但我已经只是使用向量来填充地图,因此必须有一种更合乎逻辑的方法来执行此操作。

谢谢!你们总是那么乐于助人!

请注意:如果答案不是简单的格式错误,请不要更正代码,只需指出正确的方向即可。这是一个分级作业,我是一个诚实的学生,我想自己学习。


好的,从回复和重新阅读某人发布的 SO 帖子。

  1. Visual Studio 不支持这一点,即使它在 C++ 2011 中有效

谢谢大家,我想我只需要制作一个数组。

我的教授告诉我这样做与此类似,他使用了一些支持此功能的 Linux gcc 编译器。

编辑:好的,所以微软有一个支持这个的 alpha 版本。我想我会做一个数组并转移它。

谢谢您的帮助!!!!

4

5 回答 5

4

vc++ 不支持初始化列表。
不知道update 2是否支持,但标准库肯定不支持,即使有这个特性。

编辑:更新 2 也不支持初始化列表。

于 2013-04-18T16:09:56.453 回答
1

Your code is valid C++11, but apparently your toolchain is not happy with this (mine is, by the way, Apple LLVM 4.2 Clang). Consider this as an alternative:

Lexer::Lexer(istream &source1, ostream& listing1)
    :source(source1), listing(listing1)
{
    static const char *reserved[] =
    {
        "and", "begin", "boolean", "break", "call",
        "end", "else", "false", "halt", "if", "input",
        "integer", "is", "loop", "not", "null", "newline",
        "or", "output", "procedure", "return", "then",
        "true", "var"
    };

    std::copy(std::begin(reserved), std::end(reserved),
              back_inserter(tokenToStringVector));

    // rest of your code.
}

Note: I took the liberty of fixing the merged "procedure" and "return" strings, which I'm fairly sure you neglected to separate with a , by accident.

于 2013-04-18T16:17:15.537 回答
1

对于旧 C++,唯一的选择是:

const char *constants[] = { "and", "begin", "boolean", "break", "call", "end", "else", "false", "halt",
    "if", "input", "integer", "is", "loop", "not", "null", "newline", "or", "output", "procedure"
    "return", "then", "true", "var" };

vector<string> values(constants,&constants[sizeof(constants)/sizeof(constants[0])]);
于 2013-04-18T16:14:00.637 回答
0

错误消息说明了问题。您正在尝试使用初始化列表初始化字符串向量,就好像它是一个数组一样。您可以使用初始化列表初始化数组,但不能使用向量。可能你想要的是从你的初始化列表创建一个数组,然后从你的数组初始化向量。

于 2013-04-18T16:08:20.303 回答
0

语法var = { x, y, z }只能用于聚合,并且您的编译器抗议(对他而言)vector<string>不是聚合。

于 2013-04-18T16:09:27.230 回答