赞
踩
std::copy是C++标准库中的一种算法,它用于将一个范围内的元素从一个位置复制到另一个位置。其函数原型如下:
- template <class InputIterator, class OutputIterator>
- OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
- 这里,first和last参数定义了源范围的开始和结束,而result参数定义了目标范围的开始。
例如,如果我们有一个输入向量v1,我们想将其内容复制到另一个向量v2中,我们可以这样使用std::copy:
- std::vector<int> v1 = {1, 2, 3, 4, 5};
- std::vector<int> v2(v1.size());
- std::copy(v1.begin(), v1.end(), v2.begin());
在此例中,v2现在包含与v1相同的元素。
需要注意的是,如果目标范围与源范围有重叠,则使用std::copy可能会导致未定义的行为。在这种情况下,应使用std::copy_if或其他更安全的复制方法。
此外,还可以使用带有两个迭代器对的std::copy来复制一部分序列。例如,要从向量的中间部分开始复制到最后,可以这样做:
- std::vector<int> v = {1, 2, 3, 4, 5};
- std::vector<int> target(v.size());
- std::copy(v.begin() + 1, v.end(), target.begin());
即使std::vector存储复合类型该函数依然可以使用,目前亲测vector存入结构体变量,比如存入vector的是一个结构体且结构体中嵌套结构体照样可有效;代码如下
- #include <iostream>
- #include <vector>
-
- struct DPoint2d
- {
- union
- {
- int m_xy[2];
- struct
- {
- int X;
- int Y;
- };
- };
- };
- enum DLineType
- {
- ltLine,
- ltArc
- };
- struct Arc2dStru
- {
- //! 圆心
- DPoint2d m_CenterPt;
- //! 半径,需大于 0
- double m_Radius;
- //! 半径乘以圆心角的范围,Range.Max - Range.Min <= Radius * M_2PI
- //! 时钟方向,false : 逆时针, true : 顺时针
- bool m_Clockwise;
- //! 默认构造函数
- Arc2dStru() : m_Radius(0), m_Clockwise(false) {}
-
- Arc2dStru& operator =(const Arc2dStru& AStruSrc)
- {
- m_CenterPt = AStruSrc.m_CenterPt;
- m_Radius = AStruSrc.m_Radius;
- m_Clockwise = AStruSrc.m_Clockwise;
- return *this;
- }
- };
- struct DVertex
- {
- public:
- DPoint2d Point;
- DLineType LineType;
- Arc2dStru ArcStructInfo;
- public:
- DVertex(const DLineType& lineTpye, const DPoint2d& Pt, const Arc2dStru AArcStructInfo) {
- LineType = lineTpye;
- Point = Pt;
- ArcStructInfo = AArcStructInfo;
- };
- DVertex() {};
- };
-
- int main() {
- // 创建一个源向量
- std::vector<DVertex> source;
- DVertex vertext;
- vertext.LineType = ltArc;
- vertext.Point.X = 1;
- vertext.Point.Y = 1;
- source.push_back(vertext);
- vertext.LineType = ltLine;
- vertext.Point.X = 5;
- vertext.Point.Y = 5;
- source.push_back(vertext);
- // 创建一个目标向量,其大小等于源向量的大小
- std::vector<DVertex> destination(source.size());
-
- // 使用std::copy算法复制数据
- std::copy(source.begin(), source.end(), destination.begin());
-
- // 打印目标向量的内容,以验证复制是否成功
- for (const auto& vertex : destination) {
- std::cout << "Point: " << vertex.Point.X << ", " << vertex.Point.Y << ", LineType: ";
- switch (vertex.LineType)
- {
- case ltArc: std::cout << "弧线"; break;
- case ltLine: std::cout << "直线"; break;
- }
- std::cout << std::endl;
- }
- //std::cout << std::endl;
-
- return 0;
- }

输出如下:
- Point: 1, 1, LineType: 弧线
- Point: 5, 5, LineType: 直线
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。