所以我在我的程序中檢查事實時遇到問題繼承人代碼: 該向量包含3種類型的派生對象我只是想要向量中的每個基礎對象的子項。我似乎無法找到適當的語法。STLs std :: map和std :: 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++;
}
}
}
}
我不確定語法是什麼或檢查正確的對象類型背後的邏輯。
使用dynamic_cast。 derived_1 * d1; d1 = dynamic_cast(iter-> second [i]); if(d1)d1_count ++; –
user1438832
順便說一句,你需要另一個循環。第一個循環遍歷'map'的項目。需要另一個循環來遍歷'vector'的項目。 –
是的,我剛剛意識到我需要另一個循環的載體。通過矢量的語法是什麼? –