容器基础操作1

来源:互联网 发布:如何提升淘宝宝贝权重 编辑:程序博客网 时间:2024/06/05 11:57
读一组整数到 vector 对象,计算并输出每对相邻元素的和。如果读入元素个数为奇数,则提示用户最后一个元素没有求和,并输出其值。然后修改程序:头尾元素两两配对(第一个和最后一个,第二个和倒数第二个,以此类推),计算每对元素的和,并输出。
<pre name="code" class="cpp"><pre name="code" class="cpp">int main(){int a;vector<int> ivec;while(cin>>a)ivec.push_back(a);if(ivec.size()==0)return -1;if(ivec.size()%2!=0){for(vector<int>::size_type idx=0;idx!=ivec.size()-1;idx=idx+2){cout<<ivec[idx]+ivec[idx+1]<<"\t";}cout<<"the last has not been sumed and it is"<<" "<<ivec[ivec.size()-1]<<endl;}if(ivec.size()%2==0){   for(vector<int>::size_type idx=0;idx!=ivec.size();idx=idx+2)cout<<ivec[idx]+ivec[idx+1]<<"\t";}}

int main(){int a;vector<int> ivec;while(cin>>a)ivec.push_back(a);if(ivec.size()==0)return -1;if(ivec.size()%2!=0){   vector<int>::size_type first=0,last=ivec.size()-1;   //注意for语句的语句作用域for(;first<last;++first,--last){cout<<ivec[first]+ivec[last]<<"\t";}if(first==last) cout<<"the middle has not been sumed and it is"<<" "<<ivec[first]<<endl;}if(ivec.size()%2==0){   for(vector<int>::size_type first=0,last=ivec.size()-1;first<last;++first,--last)cout<<ivec[first]+ivec[last]<<"\t";}}


                                             
0 0
原创粉丝点击