C++,什么时候应该返回引用?

标签 c++ sorting vector stl

class Node{   
private:    
vector<Node*> children;    

public:     
vector< Node* > getChildren ();    
//or    
vector< Node* >& getChildren();
}    

在 Main 函数的某处我有 STL 排序:

**stl::sort((n->getChildren()).begin(),(n->getChildren()).end(),comp);**

问题来了,如果使用 vector< Node* > getChildren() 代码会出现多余的问题,只有使用 vector< Node* >& getChildren() 才有效。 我很困惑,为什么在这种情况下只有引用有效?

最佳答案

当您不返回引用时,getChildren 将在每次调用时返回 vector 的新拷贝。

这意味着在这一行中:

stl::sort((n->getChildren()).begin(),(n->getChildren()).end(),comp);

第一次调用 getChildren 返回的拷贝与第二次调用 getChildren 的拷贝不同。这意味着 begin()end() 位于不同的 vector 上,因此您永远无法从一个 vector 迭代到另一个 vector 。

当您返回一个引用时,两个调用都返回对同一 vector 的引用,因此您可以从 begin() 迭代到 end()

关于C++,什么时候应该返回引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34013463/

相关文章:

c++ - 虚幻引擎4 :how can I calculate the new vector after rotate and translate a distance from source vector

c++ - push_back 非指针元素到一行中的 vector

c++ - 我应该如何修复 valgrind 的未初始化值错误?

C++ wininet 以 513 字节 block 获取数据

sorting - 如何进行默认多排序?

javascript - diff 2 数组,其中的项目只是重新排序

c++ - vector 和抽象类

c++ - 从一个值和一个大小创建递归函数参数列表

c++ - 计算变化数组中的预期反转次数

ruby-on-rails - 与 ransack 排序不同