简体   繁体   中英

Why do I get “Expected ;” error and “Variable not declared in scope” error?

i have following code

#include <iostream>
#include <set>
#include <string>
using namespace std;

template<class  Container>
void print(const Container &c)
{

   Container::const_iterator itr;
   for (itr=c.begin();itr!=c.end();itr++){
      cout<<*itr<< '\n';
}

}

int main(){

   set<string,greater<string>>s;
   s.insert("georgia");
   s.insert("saqartvelo");
   print(s);
   return 0;

}

but errors are

reverse.cpp: In function ‘void print(const Container&)’:
reverse.cpp:9: error: expected ‘;’ before ‘itr’
reverse.cpp:10: error: ‘itr’ was not declared in this scope
reverse.cpp: In function ‘int main()’:
reverse.cpp:17: error: ‘s’ was not declared in this scope
reverse.cpp:17: error: ‘>>’ should be ‘> >’ within a nested template argument list

What might cause this and how do I solve it?

You need typename Container::const_iterator instead of Container::const_iterator .

At the point the compiler is reading your code, it doesn't know that Container has such a type (it is a so-called dependent name).

Alexandre is right about the first two errors. The last two are due to an annoying syntax limitation of C++: you need to have a space in between the two closing brackets in the template expression:

set<string,greater<string> > s;

Otherwise, C++ interprets it as the right shift >> operator.

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