سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top