关于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