vector 操作2

//读一组整数到vector 对象,计算并输出每对相邻元素的和。如果读入元素个数为奇数,则提示用户最后一个元素没有求和,并输出其值。
//然后修改程序:头尾元素两两配对(第一个和最后一个,第二个和倒数第二个,以此类推),计算每对元素的和,并输出。


//读一组整数到vector 对象,计算并输出每对相邻元素的和
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;

//读入数据到vector对象
cout<<"Enter numbers(Ctrl+Z to end): "<<endl;
while (cin>>ival)
{
ivec.push_back(ival);
}


if (ivec.size() == 0)
{
cout<<"No elements?!"<<endl;
return -1;
}


//计算相邻的元素的和并输出
cout << "Sum of each pair of adjacent elements in the vector: "<< endl;
for (vector<int>::size_type ix = 0; ix<ivec.size()-1; ix=ix+2)
{
cout<<ivec[ix]+ivec[ix+1]<<"\t";
if ((ix+2) % 12 == 0)  //每行输出6个和
{
cout<<endl;
}
}


//提示最后一个元素没有求和
if (ivec.size()%2 != 0)
{
cout << endl
<< "The last element is not been summed "
<< "and its value is "
<< ivec[ivec.size()-1] << endl;
}
return 0;
}


//读一组整数到vector 对象,计算首尾配对元素的和并输出
#include <iostream>
#include <vector>
using namespace std;
int main()

{

vector<int> ivec;

int ival;


//读入数据到vector对象

cout<<"Enter numbers(Ctrl+Z to end): "<<endl;
while (cin>>ival)
{

ivec.push_back(ival);

}


if (ivec.size() == 0)
{

cout<<"No elements?!"<<endl;

return -1;

}


//计算相邻的元素的和并输出
cout << "Sum of each pair of counterpart elements in the vector: "<< endl;
vector<int>::size_type num = 0;
for (vector<int>::size_type first = 0, last = ivec.size()-1; first<last; ++first,--last)
{

cout<<ivec[first]+ivec[last]<<"\t";

++num;

if (num % 6 == 0)  //每行输出6个和

{

cout<<endl;

}

}


//提示居中元素没有求和
if (ivec.size()%2 != 0)
{

cout << endl

<< "The center element is not been summed "

<< "and its value is "

<< ivec[(ivec.size()-1)/2] << endl;

}
return 0;

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值