赞
踩
正向(从前向后的顺序)拷贝/移动操作,将一个容器元素拷贝/移动到另一容器中。
- #include <iostream>
- #include <vector>
- #include <algorithm>
-
- int main() {
- std::vector<std::string> data{ "a", "b", "c", "d", "e", "f"};
- for (auto v : data)
- std::cout << v << " ";
- std::cout << "\n";
-
- std::copy(data.begin(), data.begin()+3, data.begin()+3);
- for (auto v : data)
- std::cout << v << " ";
- std::cout << "\n";
-
- // Overlapping case:
- std::copy(std::next(data.begin()), data.end(), data.begin());
- for (auto v : data)
- std::cout << v << " ";
- std::cout << "\n";
- }
- #include <iostream>
- #include <vector>
- #include <iomanip>
- #include <algorithm>
-
- int main() {
- std::vector<std::string> data{ "a", "b", "c", "d", "e", "f"};
- for (auto &v : data)
- std::cout << std::quoted(v) << " ";
- std::cout << "\n";
- //"a" "b" "c" "d" "e" "f"
-
- std::move(data.begin(), data.begin()+3, data.begin()+3);
- for (auto &v : data)
- std::cout << std::quoted(v) << " ";
- std::cout << "\n";
- //"" "" "" "a" "b" "c"
- }
- #include <iostream>
- #include <vector>
- #include <algorithm>
-
- struct CopyOnly {
- CopyOnly() = default;
- CopyOnly(const CopyOnly&) = default;
- CopyOnly& operator=(const CopyOnly&) {
- std::cout << "Copy assignment.\n";
- return *this;
- };
- };
-
- int main() {
- std::vector<CopyOnly> test(6);
- //移动操作取决于底层元素类型,如果不支持移动操作,实际还是走的拷贝操作
- std::move(test.begin(), test.begin()+3, test.begin()+3);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。