首页 > 解决方案 > 当我想将数据从堆栈移动到向量时如何避免复制?

问题描述

我有一个非常常用的操作,需要将数据从堆栈移动到向量中。

让我写一个演示代码:

void handle(const std::vector<std::vector<std::pair<size_t, double>>> & v) {  // this is my handle data function

}

int main() {
  std::stack<std::vector<std::pair<size_t, double>>> data; // this is my data container, it's a stack
  int cnt = 0;
  std::vector<std::vector<std::pair<size_t, double>>> params(3);
  while (cnt++ < 3) {   // assume this handle need 3 data
    const auto & v = data.top();
    params[cnt] = v;  // i think this will involve copy operation
    // and in real scene, i need to keep params in order,
    // so i cant use emplace back, only can use [i]
    data.pop();
  }
  handle(params);
}

你能帮忙吗,我怎样才能避免复制和加速我的代码?

标签: c++c++11stl

解决方案


这就是您的代码,将创建向量的副本。

const auto & v = data.top();
params[cnt] = v;

这将通过将向量移出 来避免复制data

auto & v = data.top();
params[cnt] = std::move(v);

在 cpprefernce中,这两种操作都被描述为形式 (1) 和 (2) 。


推荐阅读