C++11中初始化字符串列表

5

我试图使用以下代码初始化一个字符串列表,在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;
 }

I/O is

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

这不是问题,但你真的需要 std::endl 提供的额外功能吗?'\n' 可以结束一行。 - Pete Becker
2
要获取列表 l 中元素的数量,请调用 l.size()sizeof 舞蹈只适用于 C 风格数组。 - Pete Becker
您的错误信息似乎在告诉您,您正在使用C++98而不是11进行构建。 - Alex Zywicki
4个回答

11

您正在使用c++98的编译器而不是c++11的编译器。如果您正在使用gcc,则可以使用以下命令:

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

您可以将c++11替换为gnu++11


谢谢,我几乎没有意识到我没有使用c++11,我想我可能害怕看到的错误数量,没有发现这个问题。 - Aparna Chaganti

10

列表初始化器仅适用于C++11。要使用C++11,您可能需要向编译器传递一个标志。对于GCC和Clang,这是-std=c++11

此外,std::list不提供下标运算符。您可以像其他答案中那样使用std::vector,或者使用范围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';
}

为什么你永远不应该使用 using namespace std? - Makogan
1
@Makogan 请查看链接。 - Henri Menke

0
这里最大的问题是你正在使用列表。在C++中,列表是双向链表,因此[]没有任何意义。你应该使用向量代替。
我建议尝试:
#include<string>
#include<vector>
#include<iostream>
using namespace std;

int main() {
      string s = "Mark";
      vector<string> l = {"name of the guy"," is Mark"};
      cout<<s<<endl;
      for (int i=0;i<l.size();i++) {
             cout<<l[i]<<endl;
      }
      return 0;
 }

替代方案

编辑:正如其他人指出的那样,请确保您正在使用c++ 11而不是c++ 98进行编译。


谢谢!那么使用列表的用例是什么呢?如果不太复杂,您能否解释一下? - Aparna Chaganti
你知道链表是什么吗? - Makogan
我明白,只是“list”这个术语对我来说太直接和引人注目了,以至于在“常规”情况下使用它。我想我是在问为什么有人会将双向链表命名为“list”? - Aparna Chaganti
@AparnaChaganti 以下问题的答案应该会有所帮助:STL中的vector vs. list - Blastfurnace

0

这个问题的答案就是简单地将一个列表的内容复制到另一个列表中,希望能有所帮助 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接