當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ copy_n()用法及代碼示例

C++ 算法 copy_n() 函數指定要複製到新容器中的元素數量。該函數用於從結果開始將容器 [first,last) 的 n 個元素複製到不同的容器中。

用法

template<class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);

參數

first:它是範圍​​的第一個元素的輸入迭代器,其中元素本身包含在範圍內。

last: 它是範圍最後一個元素的輸入迭代器,其中元素本身不包含在範圍內。

result:它是複製元素的新容器的第一個元素的輸出迭代器。

返回值

返回以結果開頭的新範圍的最後一個元素的迭代器。

例子1

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
    vector<int> u1 = {2,6,8,4,9,4};
    vector<int> u2(6);
    vector<int> u3(6);
    copy(u1.begin(), u1.begin()+3, u2.begin());
    cout<<"The new vector with copy contains:";
    for(int k=0; k<u2.size(); k++)
    cout<<u2[k]<<" ";
    copy_n(u1.begin(),4,u3.begin());
    cout<<"\n";
    cout<<"The new vector using copy_n contains:";
    for(int m=0; m<u3.size(); m++)
    cout<<u3[m]<<" ";
}

輸出:

The new vector with copy contains:2 6 8 0 0 0 
The new vector using copy_n contains:2 6 8 4 0 0

例子2

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
    int newints[]={15,25,35,45,55,65,75};
    std::vector<int> newvector;
    newvector.resize(7);
    std::copy_n(newints,7,newvector.begin());
    std::cout<<"newvector contains:";
    for(std::vector<int>::iterator  ti= newvector.begin(); ti!=newvector.end();++ti)
    std::cout<<" "<<*ti;
    std::cout<<"\n";
    return 0;
}

輸出:

newvector contains:15 25 35 45 55 65 75

複雜度

函數的複雜度從第一個元素到最後一個元素是線性的。

數據競爭

最多訪問容器的 n 個元素。

異常

如果任何容器元素拋出一個異常,該函數就會拋出異常。






相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Functions copy_n()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。