Reputation: 1
I have these classes:
class PC
{
public:
PC(string in_operatingSystem,int in_ramSlots,int in_pcieSlots,int in_totalRamSlots, int in_gbPerRam, int in_cpu, int in_ssd, int in_cost);
virtual void Print() = 0;
virtual void Upgrade() = 0;
protected:
string operatingSystem;
int ramSlots,pcieSlots,totalRamSlots,gbPerRam;
int cpu,ssd;
int cost;
};
class HomePC: public PC
{
public:
HomePC(string in_operatingSystem,int in_ramSlots,int in_pcieSlots,int in_totalRamSlots, int in_gbPerRam, int in_cpu, int in_ssd, int in_cost, string in_model);
void Print();
void Upgrade(){};
private:
string model;
};
and I'm saving the content into the vectors like this:
PCList.push_back(new HomePC("MacOS",2,0,1,4,2,256,800,Model));
I'm trying to find a way to find a specific Model(for example UserPC) in vector and erase this PC from my list.
Upvotes: 0
Views: 96
Reputation: 181
Otherwise erasing, you can try different ways
std::vector<std::unique_ptr<HomePC>> pileTemp;
std::vector<std::unique_ptr<HomePC>> pileTarget;
std::unique_ptr<HomePC> p1(new HomePC("Windows",2,0,1,4,2,256,800,"UserPC"));
pileTemp.push_back(std::move(p1));
std::unique_ptr<HomePC> p2(new HomePC("MacOs",2,0,1,4,2,256,800,"PCUser"));
pileTemp.push_back(std::move(p2));
std::for_each(pileTemp.begin(), pileTemp.end(), [&](std::unique_ptr<HomePC>& p)->void{ if(p->getmodel() != "UserPC" ) {
pileTarget.push_back(std::move(p));
}
});
Then, you can clear the temporary container.
Upvotes: 0
Reputation: 16453
You can add a getter for model
class HomePC: public PC
{
public:
HomePC(string in_operatingSystem,int in_ramSlots,int in_pcieSlots,int in_totalRamSlots, int in_gbPerRam, int in_cpu, int in_ssd, int in_cost, string in_model);
void Print();
void Upgrade(){};
std::string getModel() const { return model; }
private:
string model;
};
and dynamic cast each element:
for (auto pcIt = PCList.cbegin(); pc != PCList.cend(); ++pc) {
const auto * const homePc = dynamic_cast<HomePC *>(*pcIt);
if (homePc && homePc->getModel() == "UserPC") {
PCList.erase(pcIt);
break;
}
}
You have to add a virtual destructor to PC
otherwise you can't dynamic cast.
Upvotes: 1