简体   繁体   中英

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?

You can't write code directly like that. At the very least you need a main function. You should probably add everything (except the includes) in a main function.

You are missing a int main() function. 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.

A few notes: Don't use --(container.end()) , this can end up as undefined behavior when end is a primitive type. Use std::prev(container.end()) . Try to use the begin and end free functions as well, eg end(container) . Don't iterate with while loops, when unnecessary. Use for(auto& x : container) or for(auto it = begin(container); it != end(container); ++it) . Better yet: Use algorithms from the header algorithm .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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