算法(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构造函数初始化,没有任何参数。