2017-06-03 83 views
3

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

#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是

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

这是没有问题的,但你真的需要额外的东西,'STD: :endl'呢? ''\ n''结束一行。 –

+2

要获得列表'l'中的元素数目,请调用'l.size()'。这个'sizeof'舞蹈只适用于C风格的数组。 –

+0

您的错误消息似乎是告诉你,你正在用C++ 98而不是11 –

回答

8

您正在使用的C++ 98而不是C编译器++ 11.using这一点,如果你正在使用gcc

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

你可代替C++ 11gnu ++ 11

+0

谢谢,我几乎意识到我没有使用C++ 11,我想我害怕我看到的错误数量并且没有't赶上这一个 –

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个

+0

谢谢!,然后使用列表的用例是什么?只有在它不太复杂的情况下,你能否解释一下? –

+0

那你知道链表是​​什么吗? – Makogan

+0

我这样做,它只是“列表”这个词非常简单,并且让我可以在“常规”环境中使用它。我想我是问为什么会有人将双链表命名为“list”? –

7

列表初始化器是只适用于C++ 11。要使用C++ 11,您可能必须将标志传递给编译器。对于GCC和铛这是-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'; 
} 
+0

为什么你永远不应该使用命名空间标准? – Makogan

+0

@Makogan查看链接。 –

+1

@Makogan https://stackoverflow.com/q/1452721/1865694 –