【发布时间】:2016-11-03 07:31:59
【问题描述】:
我想从参数中获得向量的类范围别名。
例如:
class Solution {
private:
vector<int> b; // I want that &b = a, where a from function solve
int f(int i) {
// here I want to use vector<int> a,
// not passing it as a function argument every time
}
public:
int solve(vector<int>& a) {
// here I want to do smth like b = a; which works for O(1)
}
};
不幸的是,我不能只声明 vector<int> &b; ,因为错误:
declaration of reference variable 'b' requires an initializer
能否请您解释一下如何在 C++11/14 中做到这一点?
更新:我不能更改int solve(vector<int>& a)的声明,这个接口是从外部提供的。
更新:我已将代码更改为更明确。看起来我不应该再这样做了,因为在答案和 cmets 中人们使用原始变量名。对不起,对 StackOverflow 没有太多经验。
【问题讨论】:
-
“爱丽丝”是什么意思?
-
别名,抱歉,没戴眼镜没看到错字。
-
那么如果有人在拨打
solve之前拨打f会发生什么? -
也许
f是纯粹从solve内部调用的。取自“每次都不将其作为函数参数传递”,并考虑到“我无法更改int solve(vector<int>& _a)的声明,即从外部提供的接口” - 我收集solve是入口点并给出_a没有任何其他方式可用(已建议),f似乎打算在solve内使用,否则你怎么能在f中收到a? -
是的,你是对的。让我改一下代码。
标签: c++ c++11 pointers vector reference