#include <vector>
#include <cmath>
class game_npc{
private:
float base_hp=20;
float base_distance=10;
std::vector<float> hp;
std::vector<float> view_distance;
std::vector<float> X;
std::vector<float> Z;
std::vector<bool> spotted;
std::vector<float> SX;
std::vector<float> SZ;
public:
//int npcs=10;
int initialize(int);
void teleport_to_game(int,float,float);
bool inti=false;
};
int game_npc::initialize(int npcs){
for(int i=0;npcs>i;i++){
hp.push_back(base_hp);
view_distance.push_back(base_distance);//adds new element with info thats in () each loop time
spotted.push_back(false);
}
X.resize(npcs);
Z.resize(npcs);
SX.resize(npcs);
SZ.resize(npcs);
inti=true;
}
void game_npc::teleport_to_game(int _p, float _x, float _z){
X[_p]=_x;
Z[_p]=_z;
}
my code for map.h is not being used right now.
I was wondering what could cause this, why it is here. Also when the value is not 11 it works fine, even though if it is higher it does not do a sig_fault.
Avoid putting the member function definitions in the .h file. These should be put in separate .cpp files which get compiled separately then linked in to your final product.
As for the vectors, I would look at this the other way around. You have a whole host of vectors, each one to handle one piece of information for each NPC. So all the information stored in the vectors at position 1 would all refer to character 1.
I would implement this so that each NPC would be stored in its own object. Then I would have a separate class that has a vector of NPC's; this class would manage all the logic for sizing the vector, and giving references to the various NPC's that it is storing.
This way, each NPC could manage its own data and be given member functions which would manipulate the one character without risking affecting others. You only have to write vector management code once, and not for each attribute of your NPC. If you want to rewrite the way NPC's are doing things, this will not affect your vector management. etc.
You would access info this way: npc.GetAt(3).GetHP()
rather than: npc.GetHP(3)
Oh, yeah. That double free message tends to indicate that you freed unallocated memory, that is memory that was already freed. It is a little more specific than a segmentation violation.
> I run my program in a way that it gets a segmetation fault,
you run your program in a way to invoke undefined behaviour.
Undefined behaviour is undefined
Line 12 calls npc.initialize(10); which calls X.resize(npcs); to resize X to 10 items.
Then at line 13 you call npc.teleport_to_game(11/*player*/,9/*x*/,9/*z*/); which calls X[_p]=_x; to set X[11]. Since X has only 10 items X[11] doesn't exist and the program crashes.