Exercice_3.13_练习使用vetor

//读一组整数到vector对象 计算并输出每对相邻元素的和
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> ivec;
    int ival;

    //读取整数
    cout << "Enter some integers(Ctrl+Z to end). " << endl;
    while (cin >> ival)
        ivec.push_back(ival);

    //输出相邻元素和
    //先处理特殊情况
    if (ivec.size() == 0)
    {
        cout << "No elmements?!" << endl;
        return -1;
    }

    cout << "Sum of each pair of adjacent elements in the vector:" << endl;
    vector<int>::size_type cnt = 0;
    //这里必须用<ivec.size() -1 来控制循环,若采用 != ivec.size() 则可能无限循环,因为ix的自增量是2
    for (vector<int>::size_type ix = 0; ix < ivec.size() -1; ix = ix +2)
    {
        cout << ivec[ix] + ivec[ix+1] << "\t";
        ++cnt;
        if (cnt % 6 == 0)    //每行六个
            cout << endl;
    }

    if(ivec.size() % 2 != 0)
        cout << endl << "The last number is not summed, it's value is " << ivec[ivec.size()-1] << endl;

    return 0;

}

posted @ 2014-05-04 23:08  庄浩  阅读(111)  评论(0编辑  收藏  举报