简体   繁体   中英

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;
}

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_back ing 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.

Read up on the concept of pass-by-value, pass-by-reference, and pass-by-pointer. Your function getRegions is probably returning the member by value, meaning, you are creating a temporary copy, and adding australia to the copy, not the actual member.

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