1

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?

Bart
  • 19,692
  • 7
  • 68
  • 77
user466444
  • 469
  • 3
  • 7
  • 14
  • legitimate question, but tersely asked. – Alexandre C. Sep 18 '10 at 21:02
  • possible duplicate of [Error with T::iterator, where template parameter T might be vector or list](http://stackoverflow.com/questions/3735022/error-with-titerator-where-template-parameter-t-might-be-vectorint-or-listi) – Prasoon Saurav Sep 19 '10 at 02:23

2 Answers2

7

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

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
Alexandre C.
  • 55,948
  • 11
  • 128
  • 197
5

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.

Tim Yates
  • 5,151
  • 2
  • 29
  • 29