C++_vector_初探2

1. 随机生成10个数字,放入vector对象中,并使用迭代器将数字变为原来的两倍,输出。
#include <iostream>
#include <vector>
#include <string>
#include <ctime>

using namespace std;

int main(int argc, char const *argv[])
{
    vector<int> v;
    srand((unsigned)time(NULL));//生成随机数种子
    for(int i=0;i<10;i++)
    {
        v.push_back(rand()%1000);//产生1000以内的随机数,并放入v中 
    } 
    cout<<"产生的10个随机数为:";
    for(auto c:v)
        cout<<c<<" ";
        cout<<endl; 

    for(auto it=v.begin();it!=v.end();it++)
        *it*=2; 

    cout<<"扩大后的10个随机数为:";
    for(auto c:v)
        cout<<c<<" ";
        cout<<endl; 

    return 0;
}

这里使用了迭代器来改变vector容器中的值。

产生的10个随机数为:948 356 836 501 389 915 421 180 852 716
扩大后的10个随机数为:1896 712 1672 1002 778 1830 842 360 1704 1432

--------------------------------
Process exited with return value 0
Press any key to continue . . .
2. 使用迭代器求Vector中相邻两元素的和。
#include <iostream>
#include <vector>
#include <string>
#include <ctime>

using namespace std;

int main(int argc, char const *argv[])
{
    vector<int> v;
    int x=0;
    while(cin>>x)
        v.push_back(x);

    auto beg=v.begin();
    auto end=v.end();


    for(auto i=v.begin();i<beg+(end-beg)/2;i++)
    {
        cout<<*i+*(beg+(end-i)-1)<<" ";
    }

    if((end-beg)%2!=0)
        cout<<*(beg+(end-beg)/2)<<endl;


    return 0;
}

这里的迭代器使用要注意,begin()指向容器中第一个元素,end()指向最后一个元素的下一个位置。

1. 输入数据个数为偶数
1 3 2 9 3 2
^Z
3 6 11
--------------------------------
Process exited with return value 0
Press any key to continue . . .

2. 输入数据个数为奇数
1 9 2 4 5
^Z
6 13 2

--------------------------------
Process exited with return value 0
Press any key to continue . . .
3. 分数段统计。(百分制)
#include <iostream>
#include <vector>
#include <string>
#include <ctime>

using namespace std;

int main(int argc, char const *argv[])
{
    vector<int> v(11,0);
    int x=0;
    auto beg=v.begin();
    while(cin>>x)
        if(x<101)
            ++*(beg+x/10);

    for(auto c:v)
        cout<<c<<" ";
    cout<<endl;

    return 0;
}

这里对迭代器的使用很巧妙,来一个元素判断它属于哪个段,并将迭代器指向那个段,然后++即可。

12 45 23 7 89 99 100 0 44^Z
2 1 1 0 2 0 0 0 1 1 1

--------------------------------
Process exited with return value 0
Press any key to continue . . .
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值