Search code examples
c++classvectorpush-back

Using "push_back" for vector with "get" function C++


I have a class called "Region", and I have a class called "Map". The "Map" class has a vector of type "Region *" called "regions" as a member. In the .cpp file for the "Map" class, I have a "getRegions" function that returns this "regions" vector.

In main.cpp, I initialize a "Region *", called "australia", and then try to use the "getRegions" function to call the "push_back" function for the vector. I've never had problems with using "push_back" before, but when I test to see if this "Region *" is actually in the "regions" vector, it always comes back as empty.

CLion compiles and runs the program without any errors. Is it wrong to call the "push_back" function in conjunction with a "get" function?

Here is the driver code.

int main() {
    Map map;
    Region *australia;

    map.getRegions().push_back(australia);

    if (map.getRegions().empty()) {
        std::cout << "Empty"; //always prints this for some reason, even though I just pushed it back
    } else {
        std::cout << "Not Empty";
    }

    return 0;
}

Solution

  • Without seeing all your code it's difficult to tell, but based on your shown code, and described behavior, my guess is that your function looks something like:

    auto Map::getRegions() -> std::vector<Region>
    {
      // ...
      return regions;
    }
    

    This would mean you are making a copy of the vector, and you are push_backing onto a copy.

    Instead, you need to write it like:

    auto Map::getRegions() -> std::vector<Region> &
    {
      // ...
      return regions;
    }
    

    so that you return a reference to the regions member.