在c ++ 11中初始化字符串列表

Apa*_*nti 4 c++ list

我试图使用以下代码初始化c ++ 11中的字符串列表,并且由于各种原因而失败.错误说我需要使用构造函数来初始化列表,我应该使用类似的东西list<string> s = new list<string> [size]吗?我在这里错过了什么?

#include<string>
#include<list>
#include<iostream>
using namespace std;

int main() {
      string s = "Mark";
      list<string> l  {"name of the guy"," is Mark"};
      cout<<s<<endl;
      int size = sizeof(l)/sizeof(l[0]);
      for (int i=0;i<size;i++) {
             cout<<l[i]<<endl;
      }
      return 0;
 }
Run Code Online (Sandbox Code Playgroud)

I/O是

 strtest.cpp:8:47: error: in C++98 ‘l’ must be initialized by constructor, not 
 by ‘{...}’
 list<string> l  {"name of the guy"," is Mark"};
Run Code Online (Sandbox Code Playgroud)

小智 10

您正在使用c ++ 98而不是c ++ 11的编译器.如果您使用的是gcc,则使用此编译器

g++ -std=c++11 -o strtest strtest.cpp

你可以用gnu ++ 11替换c ++ 11


Hen*_*nke 9

列表初始化程序仅在C++ 11中可用.要使用C++ 11,您可能必须将标志传递给编译器.对于GCC和Clang来说这是-std=c++11.

此外,std::list不提供下标运算符.您可以std::vector在另一个答案中使用as,也可以使用基于范围的for循环来迭代列表.

一些提示:

#include <string>
#include <list>
#include <iostream>

int main() {
  std::string s = "Mark";
  std::list<std::string> l {"name of the guy"," is Mark"};

  for (auto const& n : l)
    std::cout << n << '\n';
}
Run Code Online (Sandbox Code Playgroud)