从迭代器获取对象

byq*_*qqu 1 c++ function set

我想从中获取对象,set<Node>但我认为我的函数给了我这个对象的副本.怎么解决?

Node findByNum(int n){
    for (set<Node>::iterator it = this->children.begin();it != this->children.end(); it++){
        if ((*it).num == n){
            return (*it);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ish*_*ael 5

解决它的最简单方法是让你的函数返回一个引用:

Node& findByNum(int n)
Run Code Online (Sandbox Code Playgroud)

只要您使用对它的引用,您就需要确保节点保留在集合中.