算法(Algorithm)

算法(Algorithm)

處理多個區間

如果某個算法用來處理多個區間,那麼當你調用它時,務必確保第二(以及其他)區間所擁有的元素個數,至少和第一區間內的元素個數相同。

要想讓目標區間夠大,你要不一開始就給他一個正確大小,要不就顯式地改變其大小。這兩個辦法都只適用於序列容器(vectors,deques,lists)。關聯式容器根本不會有此問題,因爲關聯式容器不可能被當做覆寫型算法的操作目標。

#include<iostream>

#include<vector>

#include<deque>

#include<list>

#include<string>

#include<algorithm>

using namespace std;

int main()

{

         list<int>coll;

         vector<int>coll2;

         //insertelements from 1 to 9

         for(inti=1;i<=9;++i) {

                   coll.push_back(i);

         }

         //resizedestination to have enough room for the overwriting algorithm

   coll2.resize(coll.size());

         //copyelements from first into second collection overwriting existing elements idestination

         copy(coll.begin(),coll.end(),coll2.begin());

         //createthird collection with enough room initial size is passed as parameter

         deque<int>coll3(coll.size());

         //copyelements form first into third collection

         copy(coll.begin(),coll.end(),coll3.begin());       

在這裏,resize()的作用是改變從coll2的元素個數:coll2.resize(coll.size());

Coll3則是在初始化時就指明要有足夠空間,以容納coll中的全部元素:

deque<int>coll3(coll.size());

注意,這兩種方法都會產出新元素並賦予初值。這些元素有default構造函數初始化,沒有任何參數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章