赞
踩
有的时候,我们需要提取某个现有的vector中的元素到另一个vector中,或者对多维的vector进行纬度的转换。在这种场景下,往往原始的vector中的数据可能并不需要了,为了节省内存空间,我们可以使用STL的移动语义。
实现元素移动的常见方法有3种。下面通过例子的形式说明:将设需要将现有vector(v1)的最顶层的全部元素移动到一个新的vector(v2)中。
方法1:(C++17)使用move iterator,配合insert函数。
v1.insert(v1.end(), std::make_move_iterator(v2.begin()), std::make_move_iterator(v2.end()));
方法2:使用std::move()
显式移动每一个元素。
for (auto & element : v1) {
v2.push_back(std::move(element));
}
方法3:先copy,然后erase原来vector中的元素。
v1.insert(v1.end(), v2.begin(), v2.end());
v2.erase(v2.begin(), v2.end());
方法1和方法2会保留原始vector(例子中的v1)顶层元素的占位,方法3则是彻底把原始vector中的元素删除了。
#include <iostream> #include <vector> int main(int argc, const char *argv[]) { auto * twoDVec1 = new std::vector<std::vector<int>>; std::vector<std::vector<int>> twoDVec2; for (int i = 0; i < 3; i++) { std::vector<int> tmpVec; for (int j = 0; j < 2; j++) { tmpVec.push_back(i); } twoDVec1->push_back(std::move(tmpVec)); } auto print2DimenVec = [&](const std::vector<std::vector<int>> & twoDimenVecc) { std::cout << "vector size: " << (twoDimenVecc.empty() ? 0 : twoDimenVecc.front().size()) << " x " << twoDimenVecc.size() << std::endl; for (const auto & vec : twoDimenVecc) { for (const auto & val : vec) { std::cout << val << ", "; } std::cout << std::endl; } }; std::cout << "origin twoDemenVec:" << std::endl; print2DimenVec(*twoDVec1); /** * @brief method 1 */ twoDVec2.insert(twoDVec2.end(), std::make_move_iterator(twoDVec1->begin()), std::make_move_iterator(twoDVec1->end())); /** * @brief method 2 * */ // for (auto & element : *twoDVec1) { // twoDVec2.push_back(std::move(element)); // } /** * @brief method 3 */ // twoDVec2.insert(twoDVec2.end(), // twoDVec1->begin(), twoDVec1->end()); // twoDVec1->erase(twoDVec1->begin(), twoDVec1->end()); std::cout << "moved twoDVec1:" << std::endl; print2DimenVec(*twoDVec1); delete twoDVec1; std::cout << "origin twoDVec2:" << std::endl; print2DimenVec(twoDVec2); return 0; }
方法1&2的运行结果如下:
origin twoDemenVec:
vector size: 2 x 3
0, 0,
1, 1,
2, 2,
moved twoDVec1:
vector size: 0 x 3
origin twoDVec2:
vector size: 2 x 3
0, 0,
1, 1,
2, 2,
方法3的运行结果如下:
origin twoDemenVec:
vector size: 2 x 3
0, 0,
1, 1,
2, 2,
moved twoDVec1:
vector size: 0 x 0
origin twoDVec2:
vector size: 2 x 3
0, 0,
1, 1,
2, 2,
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。