c++ - STL std::map 和 std::vector ;检查 map 中的对象类型

标签 c++ vector stl stdmap

所以我在我的程序中进行事实检查时遇到了问题,代码如下: 该 vector 包含 3 种类型的派生对象,我只想要 vector 中每个基本对象的小计。我似乎也找不到合适的语法。

class Base{
virtual void method() = 0;
}  

class derived_1 : public Base{
    virtual void method();
}
class derived_2 : public Base{
    virtual void method();
}
class derived_3 : public Base{
    virtual void method();
}
class general_class{
private: 
    //objects of derived types have been instantiated into the vector already
    map<string,vector<Base*>> base_map;

    void print(){
        //This line prints the key and size
        cout << iter->first << "    " << iter->.size();

        int d1_count = 0, d2_count = 0,d3_count = 0;

        for(iter=accounts_map.begin();iter !=accounts_map.end();iter++){

            //So I know that the loop iterates through the map
            //how do I fact check to determine which object was found?
            //The below code is incorrect

            if(iter->second[i] == (derived_1 /*"objects"*/)){
                d1_count++;
            }
            if(iter->second[i] == (derived_2 /*"objects"*/)){
                d2_count++;
            }
            if(iter->second[i] == (derived_3 /*"objects"*/)){
                d3_count++;
            }
        }
    }

}

我不确定语法是什么或检查正确对象类型背后的逻辑。

最佳答案

有很多方法可以实现您的目标。您可以扩展您的 Base 接口(interface)以返回一些对象种类标识符。另一种选择是使用 RTTI:

for(auto pObj : vector)
{
  if(dynamic_cast<derived1*>(pObj))
    d1_count++;
}

另请注意,您的接口(interface)基类定义不正确。您必须提供虚拟析构函数,否则不会调用派生类的析构函数。正确的版本应该是:

class Base{
    virtual void method() = 0;
    virtual ~Base() {};
} 

关于c++ - STL std::map 和 std::vector ;检查 map 中的对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41010673/

相关文章:

c++ - 使用在 C++ 中创建的 DLL 从 Excel 和 VBA 调用 C++ 函数

c++ - 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成空指针?

math - 查找表示从一个向量到另一个向量的旋转的四元数

c++ - 如何对 Vector 进行排序并删除其中的相同值?

c++ - 将 map 实例与临时 map 交换安全吗?

c++ - 使优先级队列限制其在 C++ 中的内存

c++ - 从 std::set 中提取仅 move 类型

c++ - 我应该怎么做而不是函数模板的部分特化?

c++ - 从对象 vector 中提取元素

C++ 函数写得不好,不知道如何简化它[初学者]