简体   繁体   中英

std::vector::push_back fails to add data to my vector

I have these two pieces of code that are messing up without throwing any errors:

The first piece is from a custom class which I am trying to push into an array.

class idRect {
    public:
        sf::FloatRect rect;
        int id;

        idRect(int _id, sf::FloatRect _rect) : id(_id), rect(_rect) {}
};

The second piece is where the function gets called.

if((deltaX + deltaY) < 500) { //Taxi distance calculation
    cout << endl << "Passed check" << endl;
    gloAreas.push_back(idRect(id, entity.getGlobalBounds()));
}

gloAreas is a globally defined vector which contains idRect objects.

As said earlier I have observed from the console that "Passed check" outputs and that the size of my vector doesn't increase EDIT: globally.

Edit: The error also seems rather random and only happens for 1 in 6 instances of the objects calling the push_back functions.

I'm using SFML for the sf::FloatRect which is basically just a vector of 4 floats. getGlobalBounds() is another function from SFML that returns the bounding rectangle of a sprite in sf::FloatRect format.

Any ideas of what is going wrong?

Sincerely, BarrensZeppelin

EDIT 2: The error seems to have erupted due to a mix between my own incompetence and std::multiset's sorting, maybe I'll come back for that in another thread ^^ (With a sscce ofc) Thank you guys for you time and help.

If gloAreas is defined as static , it won't be a true global. It will have global scope, but a copy of it will be created for each translation unit.

For a global, you need to declare it with extern and define it in a single implementation file.

Disclaimer: answer is just a guess, my crystal ball might be off today...

My crystal ball answer: You have redefined gloAreas in an interior scope, like this:

vector<idRect> gloAreas; // defines global

void F( vector<idRect> gloAreas ) // defines local instance
{
  gloAreas.push_back(); // affects local instance
  return;               // destroys local instance 
}
int main() {
  F(gloAreas); // Copies global instance to parameter
               // global remains unchanged.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM