代码之家  ›  专栏  ›  技术社区  ›  lsalamon

如何使用迭代器来解决这个问题?

  •  0
  • lsalamon  · 技术社区  · 15 年前

    编译器(VC8)错误为:

    模拟错误的源代码:
    [编辑]源代码已修复

    #include <map>
    #include <string>
    
    struct tag_data
    {
        int in;
        int on;
        std::string sn;
    };
    
    class myclass
    {
    private:
        typedef std::map<std::string, tag_data> TypeData; 
        TypeData MapStorage;
        typedef std::map<unsigned long, TypeData::iterator > TypeToThreadIterMapStorage; 
        TypeToThreadIterMapStorage ThreadIterMapStorage;
    
    public:
        bool find( std::string& k) 
        {
            TypeData::const_iterator theData ; 
            theData = MapStorage.find(k);
            //ThreadIterMapStorage [ 0 ] = MapStorage.begin();// this is ok
            ThreadIterMapStorage [ 1 ] = dynamic_cast<TypeData::iterator>(theData); // the error occurs here
            return theData != MapStorage.end();
        }
    
        virtual ~myclass(){}
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        myclass mc;
        return 0;
    }
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Ponting    15 年前

    动态强制转换语法: dynamic_cast<DerivedClassName*>(BaseClass*)

    dynamic_cast<DerivedClassNameReference>(BaseClassReference)
    

    我觉得这个密码很可疑。你想达到什么目标?为什么要使用迭代器?那没有任何意义。

    编辑 begin() 有两个重载,一个返回常量迭代器,另一个返回非常量迭代器。在您的注释代码中,因为 TypeToThreadIterMapStorage const_cast 删除对象的常量而不是 dynamic_cast . 但请注意,这是一件危险的事情。

    更简单的方法是将数据声明为非常量迭代器。

        2
  •  2
  •   Loki Astari    15 年前

    是什么让您认为TypeData::iterator和TypeData::const_iterator甚至是相关的?

    为什么不将“theData”的类型更改为迭代器?

    TypeData::iterator theData = MapStorage.find(k);