简体   繁体   English

C ++ STL列表迭代器

[英]C++ STL List Iterator

I'm trying to iterate through a string list with the following code: 我正在尝试使用以下代码遍历字符串列表:

#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);

However, upon building this, I get the error expected unqualified-id before 'while' What does this mean and how can I fix the problem? 但是,在构建此代码时,我expected unqualified-id before 'while'得到了expected unqualified-id before 'while'的错误expected unqualified-id before 'while'这意味着什么,我该如何解决该问题?

You can't write code directly like that. 您不能像那样直接编写代码。 At the very least you need a main function. 至少您需要一个main功能。 You should probably add everything (except the includes) in a main function. 您可能应该在main函数中添加所有内容(包含内容除外)。

You are missing a int main() function. 您缺少一个int main()函数。 C++ simply does not allow placing code other than static variables and declarations outside of a function, as it would be unclear when the code should actually run. C ++根本不允许将除静态变量和声明之外的代码放置在函数之外,因为尚不清楚何时应实际运行代码。

A few notes: Don't use --(container.end()) , this can end up as undefined behavior when end is a primitive type. 一些注意事项:不要使用--(container.end()) ,当end是原始类型时,这可能会成为未定义的行为。 Use std::prev(container.end()) . 使用std::prev(container.end()) Try to use the begin and end free functions as well, eg end(container) . 尝试同时使用beginend free功能,例如end(container) Don't iterate with while loops, when unnecessary. 不必要while ,不要使用while循环进行迭代。 Use for(auto& x : container) or for(auto it = begin(container); it != end(container); ++it) . 使用for(auto& x : container)for(auto it = begin(container); it != end(container); ++it) Better yet: Use algorithms from the header algorithm . 更好的是:使用标头algorithm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM