C++ 通过引用传递向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7966233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing vectors by reference
提问by SirYakalot
If I have a vector of objects in one class which I want to change in another, I would try and pass all the information by reference.
如果我想在另一个类中更改对象向量,我会尝试通过引用传递所有信息。
What exactly do I need to pass by reference though? The vector? The objects? Both?
我究竟需要通过引用传递什么?向量?对象?两个都?
Essentially what I'm asking is: What is the difference between these?
基本上我要问的是:这些之间有什么区别?
vector&<object> blah; // A reference to a vector of objects?
vector<object&> blah; // A vector of references to objects?
vector&<object&> blah; // A reference to a vector of references to objects???
I'm not actually sure how referencing of array like containers work. Are these legal?
我实际上不确定像容器这样的数组的引用是如何工作的。这些合法吗?
回答by Cat Plus Plus
vector&<object>
is a syntax error. vector<object&>
is invalid, because a vector's value type must be assignable. vector&<object&> blah
is a syntax error.
vector&<object>
是语法错误。vector<object&>
无效,因为向量的值类型必须是可分配的。vector&<object&> blah
是语法错误。
A reference to a vector is vector<T>&
.
对向量的引用是vector<T>&
。
回答by Kerrek SB
You cannot have a vector of references. Vector elements must be copyable and assignable, which references are not. So only the first option is actually an option, but it's spelled std::vector<Object> &
.
你不能有一个引用向量。向量元素必须是可复制和可分配的,而引用则不是。所以只有第一个选项实际上是一个选项,但它的拼写是std::vector<Object> &
。
Note that v[1]
already returns a referenceto the second element, so you can happily pass individual elements by reference.
请注意,v[1]
已经返回了对第二个元素的引用,因此您可以愉快地通过引用传递单个元素。
It is possible to have a vector of reference-wrappers a la std::ref
, but if you don't know what that is, you probably shouldn't be using it at this point.
可以有一个引用包装向量 a la std::ref
,但如果您不知道那是什么,那么此时您可能不应该使用它。
回答by jk.
Another option is to pass around iterators instead of containers. This is the approach the standard library takes in <algorithm>
. They are slightly more verbose at the calling site, but they have the advantage that they work for parts of a collection as well as complete collections and decouples the algorithm from the container.
另一种选择是传递迭代器而不是容器。这是标准库采用的方法<algorithm>
。它们在调用站点上稍微冗长一些,但它们的优点是它们适用于集合的一部分以及完整的集合,并将算法与容器分离。
Lastly, of course, it's worth while checking you know your algorithms as there may already be one that does what you want.
最后,当然,检查您是否了解您的算法是值得的,因为可能已经有一个可以做您想要的。