1
votes

I try to manipulate iterators.

template <typename Mytype>
class Myclass
 {
   public:
   Myclass ( const Mytype & myarg)
   {
    this->data=myarg;
   }
   ~Myclass ( void ){}
    set<int> Test ( const Mytype & myarg ) const
    {
      set<int> result;
      typename Mytype::iterator it=myarg.begin();
      return result;
    }
   private:
    //
    mutable Mytype data;
 };

This code is compiling.But when I want to use it, it is no longer compiling: here is an example:

int main()
 {
    Myclass <string> t0 ( "caacaa" );
    set<int> r=t0.Test("a");
    return 0;
 }

I now get an error:

test.cpp: In member function ‘std::set<int>
Myclass<Mytype>::Test(const Mytype&) const [with Mytype =
std::basic_string<char>]’:
test.cpp:38:26: instantiated from here
test.cpp:25:48: error: conversion from
‘std::basic_string<char>::const_iterator {aka
__gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >}’ to non-scalar type ‘std::basic_string<char>::iterator {aka
__gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ requested

I tried to figure out what was wrong but I don't understand the error.

1
try changing this line typename Mytype::iterator it=myarg.begin(); to typename Mytype::const_iterator it=myarg.begin();EdChum
@EdChum: Or even easier: auto it = myarg.begin();.rodrigo
@rodrigo yes, didn't spot the c++11 tagEdChum
It is now working. Thank you. What does the const change for the iterator?anothertest
You're not allowed to change the entry it points to, which makes sense because you passed the container as const reference.stefaanv

1 Answers

5
votes

In a const member function, the member data are const too. So you need to use const_iterator:

typename Mytype::const_iterator it = myarg.begin();

because myarg.begin() returns const iterator, because myarg is const, because member function is const.

Even better use auto:

auto it = myarg.begin(); 

But then you still need to know it is const — auto helps you to avoid typing the long name, not knowing the fact that it is const.