[英]C++ STL List Iterator
我正在嘗試使用以下代碼遍歷字符串列表:
#include<cstdlib>
#include<string>
#include<list>
using namespace std;
list<string> dict = {"aardvark", "ambulance", "canticle", "consumerism"};
list<string> bWords = {"bathos", "balderdash"};
//splice the bWords list into the appropriate spot in dict
auto iterLastB = --(bWords.end());
//find spot in dict
list<string>::iterator it = dict.begin();
while(it != dict.end()){
if(*it > *iterLastB)
break;
++it;
}
dict.splice(it, bWords);
但是,在構建此代碼時,我expected unqualified-id before 'while'
得到了expected unqualified-id before 'while'
的錯誤expected unqualified-id before 'while'
這意味着什么,我該如何解決該問題?
您不能像那樣直接編寫代碼。 至少您需要一個main
功能。 您可能應該在main
函數中添加所有內容(包含內容除外)。
您缺少一個int main()
函數。 C ++根本不允許將除靜態變量和聲明之外的代碼放置在函數之外,因為尚不清楚何時應實際運行代碼。
一些注意事項:不要使用--(container.end())
,當end
是原始類型時,這可能會成為未定義的行為。 使用std::prev(container.end())
。 嘗試同時使用begin
和end
free功能,例如end(container)
。 不必要while
,不要使用while
循環進行迭代。 使用for(auto& x : container)
或for(auto it = begin(container); it != end(container); ++it)
。 更好的是:使用標頭algorithm
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.