迭代器和模板

Iterator and templates

本文关键字:迭代器      更新时间:2023-10-16

我尝试操作迭代器。

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;
 };

此代码正在编译中。但当我想使用它时,它不再编译:这里有一个例子:

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

我现在得到一个错误:

test.cpp:在成员函数'std::set<int>我的类<Mytype>::Test(const Mytype&)const[带Mytype=std::basic_string<char>]':test.cpp:38:26:从这里实例化test.cpp:25:48:错误:从转换'std::basic_string<char>::const_iterator{aka__gnucxx::__normal_iterator<const char*,std::basic_string<char>>}"转换为非标量类型"std::basic_string<char>::迭代器__gnucxx::__normal_iterator<char*,std::basic_string<char>>}'请求

我试图弄清楚出了什么问题,但我不明白这个错误。

在const成员函数中,成员数据也是const。所以你需要使用const_iterator:

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

因为myarg.begin()返回常量迭代器,因为myarg是常量,因为成员函数是常量。

更好地使用auto:

auto it = myarg.begin(); 

但您仍然需要知道it是常量—auto有助于避免键入长名称,而不知道it是常量。