当前位置:   article > 正文

C++ STL copy, move 用法

C++ STL copy, move 用法

一:功能

        正向(从前向后的顺序)拷贝/移动操作,将一个容器元素拷贝/移动到另一容器中。

二:用法

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. int main() {
  5. std::vector<std::string> data{ "a", "b", "c", "d", "e", "f"};
  6. for (auto v : data)
  7. std::cout << v << " ";
  8. std::cout << "\n";
  9. std::copy(data.begin(), data.begin()+3, data.begin()+3);
  10. for (auto v : data)
  11. std::cout << v << " ";
  12. std::cout << "\n";
  13. // Overlapping case:
  14. std::copy(std::next(data.begin()), data.end(), data.begin());
  15. for (auto v : data)
  16. std::cout << v << " ";
  17. std::cout << "\n";
  18. }
  1. #include <iostream>
  2. #include <vector>
  3. #include <iomanip>
  4. #include <algorithm>
  5. int main() {
  6. std::vector<std::string> data{ "a", "b", "c", "d", "e", "f"};
  7. for (auto &v : data)
  8. std::cout << std::quoted(v) << " ";
  9. std::cout << "\n";
  10. //"a" "b" "c" "d" "e" "f"
  11. std::move(data.begin(), data.begin()+3, data.begin()+3);
  12. for (auto &v : data)
  13. std::cout << std::quoted(v) << " ";
  14. std::cout << "\n";
  15. //"" "" "" "a" "b" "c"
  16. }
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. struct CopyOnly {
  5. CopyOnly() = default;
  6. CopyOnly(const CopyOnly&) = default;
  7. CopyOnly& operator=(const CopyOnly&) {
  8. std::cout << "Copy assignment.\n";
  9. return *this;
  10. };
  11. };
  12. int main() {
  13. std::vector<CopyOnly> test(6);
  14. //移动操作取决于底层元素类型,如果不支持移动操作,实际还是走的拷贝操作
  15. std::move(test.begin(), test.begin()+3, test.begin()+3);
  16. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/934020
推荐阅读
相关标签
  

闽ICP备14008679号