0

I have a problem with accessing shared_ptr Vector from main. My turnOrder function takes 2 sharedPtr vectors, combines and sorts them and puts the objects to another vector(Units).The problem is, when I test the function using for loops it gives exactly what I want but in the int main(), Units vector seems empty and when I try to access any object it gives this exit code: " exit code -1073741819 (0xC0000005) ".

void turnOrder( std::vector<std::shared_ptr<Monster>> monsters, std::vector<std::shared_ptr<Hero>> heroes,  std::vector<std::shared_ptr<Unit>> Units) {

    std::vector<std::shared_ptr<Unit>> units;

    units.reserve(8);

    units.insert(units.begin(), heroes.begin(), heroes.end());
    units.insert(units.end(), monsters.begin(), monsters.end());
//TESTING INITIAL VECTOR

    for(int i = 0; i < units.size(); i++){
        units[i]->printOut();
    }
    for (int i = 0; i < units.size(); i++) {
        units[i]->findSpeedRate();
    }
    struct X{

        inline bool operator() ( const std::shared_ptr<Unit> obj1, const std::shared_ptr<Unit> obj2){
            return(obj1->speedRate > obj2->speedRate);
        }
    };
    std::sort(units.begin(), units.end(), X());

    for(int i = 0; i < units.size(); i++){
        Units.emplace_back(units[i]);
    }

//TESTING ORDERED VECTOR
    for(int i = 0; i < Units.size(); i++){
        Units[i]->printOut();
    }

}


int main(){

    std::vector<std::shared_ptr<Unit>> Units;
    std::vector<std::shared_ptr<Monster>> monsters;
    std::vector<std::shared_ptr<Hero>> heroes;

    auto crusader1 = std::make_shared<Crusader>(1);
    heroes.emplace_back(crusader1);
//It goes the same with the other objects(monsters and heroes)

    turnOrder(monsters, heroes, Units);
    Units[0]->printOut();


}
0

2 Answers 2

1

Pass vectors by reference, not by value. You are modifying copies of vectors inside the turnOrder. Simply change the declaration to

void turnOrder( std::vector<std::shared_ptr<Monster>>& monsters, std::vector<std::shared_ptr<Hero>>& heroes,  std::vector<std::shared_ptr<Unit>>& Units) {...}

The difference is & for each variable. Also, please refer for this question for additional info.

Sign up to request clarification or add additional context in comments.

Comments

0

The other poster has a point about copies but I would take a look at this and say if you are going to populate units in this function why not just return units and remove the units parameter. Then

Units=turnOrder(monsters, heroes)

makes lots of sense.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.