歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 簡單的程序诠釋C++ STL算法系列之copy

簡單的程序诠釋C++ STL算法系列之copy

日期:2017/3/1 9:38:01   编辑:Linux編程

現在我們來看看變易算法。所謂變易算法(Mutating algorithms)就是一組能夠修改容器元素數據的模板函數,可進行序列數據的復制,變換等。

我們現在來看看第一個變易算法:元素復制算法copy。該算法主要用於容器之間元素的拷貝,即將迭代器區間[first,last)的元素復制到由復制目標result給定的區間[result,result+(last-first))中。下面我們來看看它的函數原型:

函數原形:

template<class InputIterator, class OutputIterator>
OutputIterator copy(
InputIterator _First,
InputIterator _Last,
OutputIterator _DestBeg
);

參數

_First, _Last

指出被復制的元素的區間范圍[ _First,_Last).

_DestBeg

指出復制到的目標區間起始位置

返回值

返回一個迭代器,指出已被復制元素區間的最後一個位置

程序示例:

首先我們來一個簡單的示例,定義一個簡單的整形數組myints,將其所有元素復制到容器myvector中,並將數組向左移動一位。

/*******************************************************************
* Copyright (C) Jerry Jiang
*
* File Name : copy01.cpp
* Author : Jerry Jiang
* Create Time : 2012-3-20 22:44:28
* Mail : [email protected]
* Blog : http://www.linuxidc.com
*
* Description : 簡單的程序诠釋C++ STL算法系列
* 變易算法 : 元素復制copy
*
******************************************************************/

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main ()
{
int myints[] = {10, 20, 30, 40, 50, 60, 70};
vector<int> myvector;
vector<int>::iterator it;

myvector.resize(7); // 為容器myvector分配空間

//copy用法一:
//將數組myints中的七個元素復制到myvector容器中
copy ( myints, myints+7, myvector.begin() );

cout << "myvector contains: ";
for ( it = myvector.begin(); it != myvector.end(); ++it )
{
cout << " " << *it;
}
cout << endl;

//copy用法二:
//將數組myints中的元素向左移動一位
copy(myints + 1, myints + 7, myints);

cout << "myints contains: ";
for ( size_t i = 0; i < 7; ++i )
{
cout << " " << myints[i];
}
cout << endl;

return 0;
}

從上例中我們看出copy算法可以很簡單地將一個容器裡面的元素復制至另一個目標容器中,上例中代碼特別要注意一點就是myvector.resize(7);這行代碼,在這裡一定要先為vector分配空間,否則程序會崩,這是初學者經常犯的一個錯誤。其實copy函數最大的威力是結合標准輸入輸出迭代器的時候,我們通過下面這個示例就可以看出它的威力了。

/*******************************************************************
* Copyright (C) Jerry Jiang
*
* File Name : copy2.cpp
* Author : Jerry Jiang
* Create Time : 2012-3-20 23:25:29
* Mail : [email protected]
* Blog : http://www.linuxidc.com
*
* Description : 簡單的程序诠釋C++ STL算法系列
* 變易算法 : 元素復制copy
*
******************************************************************/

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <string>

using namespace std;

int main ()
{
typedef vector<int> IntVector;
typedef istream_iterator<int> IstreamItr;
typedef ostream_iterator<int> OstreamItr;
typedef back_insert_iterator< IntVector > BackInsItr;

IntVector myvector;

// 從標准輸入設備讀入整數
// 直到輸入的是非整型數據為止 請輸入整數序列,按任意非數字鍵並回車結束輸入
cout << "Please input element:" << endl;
copy(IstreamItr(cin), IstreamItr(), BackInsItr(myvector));

//輸出容器裡的所有元素,元素之間用空格隔開
cout << "Output : " << endl;
copy(myvector.begin(), myvector.end(), OstreamItr(cout, " "));
cout << endl;

return 0;
}

呵呵,現在知道copy的神奇所在吧,^_^

Copyright © Linux教程網 All Rights Reserved