C++ 关于vector的两个练习

vi插入五个整数,删除里面的奇数,然后输出结果

#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;

int main()
{
   vector<int>vi;
   int a[5] ;
    for(int i=0;i<5;i++)
    {
        cin>>a[i];
        vi.push_back(a[i]);
    }       
    vector<int>::iterator it;
	cout<<"the old num: ";
    for(auto it=vi.begin();it !=vi.end();)
    {
	    cout<<*it<<" ";
        if((*it)% 2 ==1)
            vi.erase(it);
        else
            it++;
    }
        putchar('\n');
	cout<<"the new num: ";
    for(auto it=vi.begin();it !=vi.end();it++)
    {
	cout<<*it<<" ";
    }
    putchar('\n');
}

运行结果:

10 99 51 12 3
the old num: 10 99 51 12 3 
the new num: 10 12 

vs插入五个字符串,删除字符串中后缀为奇数的字符串,然后输出结果

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> vs;
    string str;
    for(int i=0;i<5;i++)
    {
        cin>>str;
        vs.push_back(str);
    }
    vector<string>::iterator it;
    cout<<"the old string: ";
    for(auto it=vs.begin();it !=vs.end();it++)
	cout<<*it<<" ";
    putchar('\n');
    cout<<"the new string: ";
    for(auto it=vs.begin();it!=vs.end();it++)
    {
        auto it2 = (*it).end()-1;
        if((*it2)%2==0)
        {
            cout<<*it<<" ";
        }
    }
    putchar('\n');
}

运行结果

q1 w2 e3 r4 t5
the old string: q1 w2 e3 r4 t5 
the new string: w2 r4 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值