赞
踩
注意:std::copy只负责复制,不负责申请空间,所以复制前必须有足够的空间!!!
std::copy的函数形式为:
std::copy(src_start_iter, src_end_iter, std::back_inserter(dst_container));
以下为写的测试代码:
- #include <iostream>
- #include <string>
- #include <algorithm>
- #include <vector>
- #include <set>
- #include <map>
-
- void stdCopyTest()
- {
- // vector copy to vector
- {
- std::vector<int> vtSrc = { 1, 2, 3, 4, 5 };
- std::vector<int> vtDst(6, 0); // std::vector(size, init_data), insert into begin,it must be new enough space first.
- std::copy(vtSrc.begin(), vtSrc.end(), vtDst.begin());
- for (size_t i = 0, uSize = vtDst.size(); i < uSize; ++i)
- {
- std::cout << vtDst[i] << '\t';
- }
- std::cout << std::endl;
-
- std::vector<int> vtDst01(0);
- std::copy(vtSrc.begin(), vtSrc.end(), std::back_inserter(vtDst01));
- for (size_t i = 0, uSize = vtDst01.size(); i < uSize; ++i)
- {
- std::cout << vtDst01[i] << '\t';
- }
- std::cout << std::endl;
- }
-
- // set insert into vector
- {
- std::set<int> setSrc = { 5, 4, 3, 2, 1 };
- std::vector<int> vtDst;
- std::copy(setSrc.begin(), setSrc.end(), std::back_inserter(vtDst));
- for (size_t i = 0, uSize = vtDst.size(); i < uSize; ++i)
- {
- std::cout << vtDst[i] << '\t';
- }
- std::cout << std::endl;
- }
-
- // array insert into vector
- {
- int szSrc[5] = { 1, 2, 3, 4, 5 };
- std::vector<int> vtDst;
- std::copy(szSrc, szSrc + sizeof(szSrc) / sizeof(int), std::back_inserter(vtDst));
- for (size_t i = 0, uSize = vtDst.size(); i < uSize; ++i)
- {
- std::cout << vtDst[i] << '\t';
- }
- std::cout << std::endl;
- }
-
- // vector insert into array
- {
- std::vector<int> vtSrc = { 1, 2, 3, 4, 5 };
- int szDst[8] = { -1 };
- std::copy(vtSrc.begin(), vtSrc.end(), szDst);
- for (size_t i = 0, uSize = vtSrc.size(); i < uSize; ++i)
- {
- std::cout << szDst[i] << '\t';
- }
- std::cout << std::endl;
- }
-
- // array insert into array
- {
- int szSrc[5] = { 1, 2, 3, 4, 5 };
- int szDst[8] = { -1 };
- std::copy(szSrc, szSrc + sizeof(szSrc) / sizeof(int), szDst);
-
- for (size_t i = 0, uSize = sizeof(szSrc) / sizeof(int); i < uSize; ++i)
- {
- std::cout << szDst[i] << '\t';
- }
- std::cout << std::endl;
- }
-
- // map copy to map
- {
- std::map<int, std::string> mp4Src =
- {
- std::pair<int, std::string>(1, "abc123"),
- std::pair<int, std::string>(2, "bcd456"),
- std::pair<int, std::string>(3, "cde789"),
- };
-
- std::cout << "***********************" << std::endl;
- std::map<int, std::string> mp4Dst;
- mp4Dst.insert(mp4Src.begin(), mp4Src.end());
- for (auto iter = mp4Dst.begin(); iter != mp4Dst.end(); ++iter)
- {
- std::cout << iter->first << ": " << iter->second << std::endl;
- }
- std::cout << "***********************" << std::endl;
- }
-
- return;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。