0

我需要以这种方式在类中初始化向量

vector<string> test("hello","world");

但是当我这样做时,编译器将它识别为一个函数并给我错误之类的错误:字符串常量之前的预期标识符等。

当我这样做时

vector<string> test = ("hello","world") 

没关系..有什么办法可以做到vector<string> test("xx")吗?

4

1 回答 1

5

std::vector 中没有这样的构造函数可以让你像那样初始化它。您的第二个示例评估为"world"(这就是,运算符所做的),这就是向量中的结果。

如果要在声明时初始化向量,请使用初始化列表:

vector<string> test = {"hello", "world"};

确保以 C++-11 模式构建源代码以使其正常工作。如果您没有与 C++-11 兼容的编译器,则必须在之后将值添加到向量中:

vector<string> test;
test.push_back("hello");
test.push_back("world");
于 2012-11-30T18:07:41.273 回答