c++ - 如何通过引用 O(1) 在 C++ 中复制 vector ?

标签 c++ c++11 pointers vector reference

我想从参数中为 vector 设置类范围别名。

对于exapmale:

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) 的声明, 外部提供的接口(interface)。

更新:我已将代码更改为更明确。看起来我不应该再做一次,因为在答案和评论中人们使用原始变量名。对不起,对 StackOverflow 没有太多经验。

最佳答案

也许是这个?

class Solution {
public:
     vector<int> a;
     int maxCoins(const vector<int>& _a) { // const because copying
          a.assign( _a.begin(), _a.end() );
     }
};

但请注意,如果您想要引用原始 vector<int>,也可以这样做而不是拷贝:

class Solution {
public:
     vector<int> & a;
     int maxCoins(vector<int>& _a) : a( _a ) {}
};

更新

这可能是最接近的。您不能重新初始化引用,但这正是指针的用例。

class Solution {
public:
     vector<int> * a;
     int f(int i) {
         a->size(); // can access indirectly
         (*a)[1]; // element access is slightly trickier
         vector<int> & _a = *a; // or can create a direct ref
         _a.size();
     }
     int solve(vector<int>& _a) {
         a = &_a; // store address to _a. a reference is like any local variable unless doing something funny
     }
};

更新 2 - 不使用指针

#include <functional>

class Solution {
public:
     // vector<int> a;
     typedef vector<int> datatype;
     datatype blankref;
     std::reference_wrapper<datatype> a = blankref;
     int f(int i) {
          vector<int> & _a = a;
     }
     int solve(vector<int>& _a) {
          a = std::ref(_a);
     }
};

您无法避免引用是一次性分配的事实。必须使用初始化语法分配类实例中的引用。要获得可重用的引用,您每次都需要有一个新初始化的对象。

为了帮助我们,感谢评论中的建议,有std::reference_wrapper<T>可以保存引用实例的类型。它可以分配给使用 std::ref( _a )反复。

老实说,如果使用得当,指针并非不雅,imo。它归结为用例和您认为您需要的东西。就性能而言,这可能不如指针好(因为正在构造临时对象),但不能保证......它在任何情况下都应该表现相似。

关于c++ - 如何通过引用 O(1) 在 C++ 中复制 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136061/

相关文章:

java - C++/Java : Toggle boolean statement?

c++ - QCustomPlot 和 iRangeDrag 在第二个右边的 yAxis

c++ - glGetError 无限返回 1282

c++ - QPrinter 在图像周围环绕文本

c++ - 如何为现有对象填充接口(interface)?

c++ - 单步构建目标时如何预编译头文件?

c++ - Windows Phone 8 上的 DirectX - 上下文/设备在最小化时丢失

c - 使用和不使用 & 传递指向函数的指针

c++ - 正确销毁指向对象的指针

具有多个指针和括号的 C 语法