i'm new to c++, i'm trying to make a for to add elements in my vector, those elements are a custom object named Peer.
i'm using Visual Studio 2015, Win32 Project..
follow my code :
Ok, i think this code isnt wrong, after this loop, i tryed to test doing this loop :
1 2 3
for each (Peer *p in peers){
MessageBox(NULL,p->getLabel(),p->getLabel(),NULL);
}
the size of vector is right, but all elements that return in this second loop are the same.. i dont know what is wrong in this code..
if someone could help my i'll be grateful!
std::vector<Peer*> peers;
int i = 0;
for (const Json::Value& json: jsonData["objt"]) {
const std::string aux(json["label"].asString());
char label[200];
strcpy_s(label, aux.c_str());
Peer *peer = new Peer();
Peer *child;
peer->setLabel(label);
//Add in vector
peers.push_back(peer);
//Popup with the right label
MessageBox(NULL,peers.at(i)->getLabel(),peers.at(i)->getLabel(),NULL);
i++;
peer = NULL;
}
//Check if the first element in vector is same of the first popup, but print the last position in vector.
MessageBox(NULL,peers.at(0)->getLabel(),peers.at(0)->getLabel(),NULL);
//dosent matter which position i try to print, always will print the last position of vector
I'm going to do a blind guess and say that that test will pass, all the output will be what was expected. The problem is in .setLabel() that simply assigns a pointer in Peer instead of copying the content.
that's your mistake.
you need to copy the content, but you are simply pointing to that memory address.
As a fix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Peer{
private:
std::string label;
void Peer::setLabel(constchar *nome){ //or ask for a std::string
label = nome; //this being std::string it will copy the content
}
constchar* Peer::getLabel() const{
return label.c_str()
}
};
//...
const std::string aux(json["label"].asString());
Peer *peer = new Peer(); //this would be better as Peer peer;
peer->setLabel( aux.c_str() );
peers.push_back(peer); //and this vector should be std::vector<Peer>
for (const Json::Value& filas : jsonData["filas"]) {
Peer *peer = new Peer();
const std::string fila(filas["nome"].asString());
peer->setLabel(fila.c_str());
peer->setNumero(NULL);
peers.push_back(peer);
//this messagebox shows ok
// MessageBox(NULL, peers.at(i)->getLabel(), peers.at(i)->getLabel(),NULL);
i++;
}
//i made this other for, for test if the results would do the same, but all messages are the last element that i push to vector
for each (Peer *p in peers)
{
MessageBox(NULL,p->getLabel(),p->getLabel(),NULL);
}