2017-06-03 89 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 –