C++标准库中copy算法的使用

简介: C++标准库中copy算法的使用

C++标准库中copy算法的使用

目录


std::copy是C++标准库中的算法接口,主要用于两个容器间的复制,据说其效率要优于自己用for循环逐个复制。之前一直非常混淆其中的用法,这里总结了几个例子如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
  //vector复制到vector
  {   
    vector<int> src = { 0, 1, 2, 3, 4 };
    vector<int> dst(8, -1);
    std::copy(src.begin(), src.end(), dst.begin());
    for (int i = 0; i < dst.size(); i++)
    {
      cout << dst[i] << '\t';
    }
    cout << endl;
  }
  //vector插入到vector末尾
  {
    vector<int> src = { 0, 1, 2, 3, 4 };
    vector<int> dst = { -10, -9 };
    std::copy(src.begin(), src.end(), std::back_inserter(dst));
    for (int i = 0; i < dst.size(); i++)
    {
      cout << dst[i] << '\t';
    }
    cout << endl;
  }
  //set插入到vector
  {
    set<int> src = { 4, 3, 2, 1, 0 };
    vector<int> dst;
    std::copy(src.begin(), src.end(), std::back_inserter(dst));
    for (int i = 0; i < dst.size(); i++)
    {
      cout << dst[i] << '\t';
    }
    cout << endl;
  }
  //数组插入到vector
  {
    int src[5] = { 0, 1, 2, 3, 4 };
    vector<int> dst;
    std::copy(src, src+5, std::back_inserter(dst));
    for (int i = 0; i < dst.size(); i++)
    {
      cout << dst[i] << '\t';
    }
    cout << endl;
  }
  //vector插入到数组
  {
    vector<int> src = { 0, 1, 2, 3, 4 };
    int dst[8] = { -1 };
    std::copy(src.begin(), src.end(), dst);
    for (int i = 0; i < 8; i++)
    {
      cout << dst[i] << '\t';
    }
    cout << endl;
  }
  //数组插入到数组
  {
    int src[5] = { 0, 1, 2, 3, 4 };
    int dst[8] = { -1 };
    std::copy(src, src + 5, dst);
    for (int i = 0; i < 8; i++)
    {
      cout << dst[i] << '\t';
    }
    cout << endl;
  }    
}

这个例子虽然繁复,但是确实表达了STL算法(algorithms)接口的原则:STL算法不负责空间申请操作,只负责相应行为,接口中容器的大小应该预先申请好。但是,这里有的例子用到了std::back_inserter,也就是插入迭代器,会将元素自动插入到支持push_back的容器后面,看起来似乎破坏了这个原则。这也是我之前为什么搞混淆的原因。看来这个问题有机会还需进一步深究。

最后的运行结果如下:

分类: C++

标签: copy , STL , C++


相关文章
|
27天前
|
存储 算法 安全
超级好用的C++实用库之sha256算法
超级好用的C++实用库之sha256算法
51 1
|
8天前
|
算法 数据处理 C++
c++ STL划分算法;partition()、partition_copy()、stable_partition()、partition_point()详解
这些算法是C++ STL中处理和组织数据的强大工具,能够高效地实现复杂的数据处理逻辑。理解它们的差异和应用场景,将有助于编写更加高效和清晰的C++代码。
8 0
|
18天前
|
存储 算法 程序员
迪杰斯特拉(Dijkstra)算法(C/C++)
迪杰斯特拉(Dijkstra)算法(C/C++)
|
18天前
|
人工智能 算法 Java
【搜索算法】数字游戏(C/C++)
【搜索算法】数字游戏(C/C++)
|
27天前
|
存储 算法 安全
超级好用的C++实用库之国密sm4算法
超级好用的C++实用库之国密sm4算法
39 0
|
27天前
|
算法 安全 Serverless
超级好用的C++实用库之国密sm3算法
超级好用的C++实用库之国密sm3算法
34 0
|
27天前
|
算法 数据安全/隐私保护 C++
超级好用的C++实用库之MD5信息摘要算法
超级好用的C++实用库之MD5信息摘要算法
48 0
|
2月前
|
算法 搜索推荐 C++
c++常见算法
C++中几种常见算法的示例代码,包括查找数组中的最大值、数组倒置以及冒泡排序算法。
21 0
|
2月前
|
算法 C++ 容器
【C++算法】双指针
【C++算法】双指针
|
3月前
|
搜索推荐 算法 C++