【问题标题】:Initializing variable in class在类中初始化变量
【发布时间】:2012-11-30 18:00:00
【问题描述】:

我需要这样在类中初始化向量

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

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

当我这样做时

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

没关系..有什么方法可以用vector&lt;string&gt; test("xx")方式做到吗?

【问题讨论】:

  • 你确定vector&lt;string&gt; test = ("hello","world") 做了你认为的事情吗?

标签: c++ string vector


【解决方案1】:

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

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

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

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

vector<string> test;
test.push_back("hello");
test.push_back("world");

【讨论】:

  • 或者只是string arr[] = {"hello","world"};vector&lt;string&gt; test(arr,arr + 2);
  • 实际上,逗号运算符也不会像您认为的那样做。他的第二个示例计算结果为“世界”。
  • 字符串 fonoArgs[] = {"1","2","3"};矢量 fonoS(fonoClass::fonoArgs,fonoClass::fonoArgs+3);这给了我错误错误:'fonoClass::fonoArgs' is not a type
  • @user1751550 我不知道fonoClass 应该是什么。无论如何,不​​要使用这种方法,因为它会以普通数组的形式引入向量的副本。这是一种浪费。只需使用初始化列表(您没有提及您正在使用的编译器。)
猜你喜欢
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 2015-04-22
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
相关资源
最近更新 更多