user466444
user466444

Reputation: 489

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?

Upvotes: 1

Views: 753

Answers (2)

Alexandre C.
Alexandre C.

Reputation: 56996

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).

Upvotes: 7

Tim Yates
Tim Yates

Reputation: 5291

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.

Upvotes: 5

Related Questions