简体   繁体   English

对带有“get”的向量使用“push_back” function C++

[英]Using “push_back” for vector with “get” function C++

I have a class called "Region", and I have a class called "Map".我有一个名为“Region”的 class,我有一个名为“Map”的 class。 The "Map" class has a vector of type "Region *" called "regions" as a member. “地图”class 有一个名为“regions”的“Region *”类型向量作为成员。 In the.cpp file for the "Map" class, I have a "getRegions" function that returns this "regions" vector.在“地图”class 的 .cpp 文件中,我有一个“getRegions”function,它返回这个“区域”向量。

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.在main.cpp中,我初始化了一个名为“australia”的“Region *”,然后尝试使用“getRegions”function调用“push_back”function为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.我以前从未遇到过使用“push_back”的问题,但是当我测试这个“Region *”是否真的在“regions”向量中时,它总是以空的形式返回。

CLion compiles and runs the program without any errors. CLion 编译并运行程序没有任何错误。 Is it wrong to call the "push_back" function in conjunction with a "get" function?将“push_back” function 与“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:没有看到你所有的代码很难说,但根据你显示的代码和描述的行为,我你的 function 看起来像:

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.这意味着您正在制作向量的副本,并且您正在push_back到副本上。

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.以便您返回对regions成员的引用。

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.您的 function getRegions可能正在按值返回成员,这意味着您正在创建一个临时副本,并将australia添加到副本中,而不是实际成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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