[英]Initializing list of strings in c++11
我試圖使用以下代碼在 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;
}
輸入/輸出是
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"};
您使用的是 c++98 而不是 c++11 的編譯器。如果您使用的是 gcc,則使用它
g++ -std=c++11 -o strtest strtest.cpp
你可以用gnu++11替換c ++11
列表初始值設定項僅在 C++11 中可用。 要使用 C++11,您可能必須將標志傳遞給編譯器。 對於GCC和 Clang,這是-std=c++11
。
此外, std::list
不提供下標運算符。 您可以像在另一個答案中一樣使用std::vector
,也可以使用基於范圍的 for 循環來遍歷列表。
還有一些提示:
using namespace std;
#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';
}
這里最大的問題是您正在使用列表。 在 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
那么這個問題的答案就是簡單地將一個列表的內容復制到另一個列表中希望它有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.