读一组整数到 vector 对象,计算并输出每对相邻元素的和。如果读入元素个数为奇数,则提示用户最后一个元素没有求和,并输出其值。然后修改程序:头尾元素两两配对(第一个和最后一个,第二个和倒数第二个,以此类推),计算每对元素的和,并输出。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> vt;
vector<int> sidesum;
vector<int> firstlast;
int ival;
//读入数据到vector对象中。
cout<<"Enter numbers(Ctrl+z to end):"<<endl;
while (cin>>ival)
{
vt.push_back(ival);
}
//计算相邻元素的和并输出
if(vt.size()==0)
{
cout<<"No element !"<<endl;
return -1;
}
cout<<"Sum of each pair of adjacent elements in the vector:"
<<endl;
cout<<"\t\t******* side bye side sum ******* "<<endl;
for (vector<int>::size_type i=0;i<vt.size()-1;i=i+2)
{
cout<<vt[i]+vt[i+1]<<'\t';
if ((i+2)%12==0)
{
cout<<endl;
}
}
cout<<endl;
cout<<endl;
if (vt.size()%2!=0)
{
cout<<endl
<<"The last element is no been summed "
<<"and it`s value is "
<<vt[vt.size()-1]<<endl;
}
cout<<"\t\t******* First and Last sum ******* "<<endl;
for (vector<int>::size_type i=0;i<vt.size()/2;++i)
{
cout<<vt[i]+vt[vt.size()-i-1]<<'\t';
if ((i+1)%6==0)
{
cout<<endl;
}
}
if (vt.size()%2!=0)
{
cout<<endl
<<"The middle element is no been summed "
<<"and it`s value is "
<<vt[vt.size()/2]<<endl;
}
return 0;
}