Per*_*ect 1 c++ stl vector stdmap
所以我在我的程序中检查事实时遇到了问题:代码:向量包含3种类型的派生对象我只想要向量中每个基础对象的子总数.我似乎无法找到适当的语法.
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++;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定语法是什么或检查正确的对象类型背后的逻辑.
有很多方法可以实现您的目标.您可以扩展您的Base界面以返回一些对象类型标识符.另一种选择是使用RTTI:
for(auto pObj : vector)
{
if(dynamic_cast<derived1*>(pObj))
d1_count++;
}
Run Code Online (Sandbox Code Playgroud)
另请注意,您的接口基类定义不正确.您必须提供虚拟析构函数,否则将不会调用派生类的析构函数.正确的版本应该是:
class Base{
virtual void method() = 0;
virtual ~Base() {};
}
Run Code Online (Sandbox Code Playgroud)