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 . . .