Hello
I'm trying to copy a variable from a vector into an array (with a few steps in between)
As you can see from the code, I take a random piece of equipment from the vector of equipments and insert it into the inventory (which is an array).
The line marked with the <---- gives a warning in the compiler.
warning: taking address of temporary
// Static list of monsters & equipment
vector<CMonster> monsters;
vector<CEquipment> equipments;
vector<CPotion> potions;
vector<CBag> bags;
template <typename T>
void load_from_file(vector<T> & v, const char * filename) {
ifstream in(filename);
if (!in.is_open())
throw runtime_error(string("File does not exist: ") + filename);
string line;
while (getline(in, line)){
if (line[0] == 'P'){
potions.push_back(CPotion(line));
}
else if (line[0] == 'Z'){
bags.push_back(CBag(line));
}
else{
v.push_back(T(line));
}
}
}
template <typename T>
T random_from(const vector<T> & v) {
return v[d(1, v.size()) - 1];
}
void Battle(CPlayer player, int count){
// code omitted
if (count > 1 and player.Alive()){
// generate an amount of gold
int amt = rand()%100;
player.Receive(amt);
cout << "You get " << amt << " gold from the " << monster.GetName() << endl;
// less money is compensated with a weapon
//if (amt < 20){
CEquipment* equipment = &(random_from<CEquipment>(equipments)); //<-----
cout << "You search the room and find: " << *equipment << "."<< endl;
cout << "What do you do? (e)quip, (c)ontinue, add to (i)nventory " << endl;
cin >> move;
switch (move){
case 'e':
player.WieldItem(*equipment);
break;
case 'i':
player.AddToInventory(equipment);
player.DispInv();
break;
default:
break;
}
//}
}
else {cout << "You survived the dungeon!" << endl << "Your final stats: " << player << endl;}
// code omitted
}
When I print out the inventory after one addition, its correct but after the second addition it says that both elements are the same and equal to the last added item.
How can I resolve this issue? I know the inventory works as it should, the display function is also correct.
I thinks its something with the fact that the equipment from the vector is given through a few functions. But I don't see the solution.
Thanks,
Jasper