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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值