c++ - 当我想将数据从堆栈移动到向量时如何避免复制?
问题描述
我有一个非常常用的操作,需要将数据从堆栈移动到向量中。
让我写一个演示代码:
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);
}
你能帮忙吗,我怎样才能避免复制和加速我的代码?
解决方案
这就是您的代码,将创建向量的副本。
const auto & v = data.top();
params[cnt] = v;
这将通过将向量移出 来避免复制data
。
auto & v = data.top();
params[cnt] = std::move(v);
在 cpprefernce中,这两种操作都被描述为形式 (1) 和 (2) 。
推荐阅读
- apache-kafka - Apache Kafka 日志保留配置问题或如何配置 Kafka 保留策略?
- java - 如何使用 Apache POI 从特定行读取特定的 excel 列
- apache-spark - spark-cassnadra 连接器问题
- python - 返回 bin 坐标 python
- python - 在 Jupyter Notebook 中创建新笔记本时出错 [权限被拒绝]
- android - 多重扩展文件
- python - Python Cocos2d 调整大小后找不到资源图像
- python - 带有 Yattag 的 HTML 表格 - 创建新的 TR
- android - 无法在 WebView 中播放带有 html 的音频链接
- z3 - Z3 求解器的低效率问题