vector 的使用方法(伪数列)

来源:互联网 发布:网络应用模型 编辑:程序博客网 时间:2024/06/01 17:40
  • 向量 vector 的使用方法:

    1. vector<T> v<vector>中定义
    2. vector<T>::size_type保存vector大小
    3. vector.begin()返回vector的第一个元素,vector.end()返回vector的最后一个元素
    4. v.push_back(e)向向量中添加一个元素,元素初始值为e
    5. v[i]返回储存在i位置的值 注:与string一样第一位为0
    6. v.size()返回元素个数
    7. sort(b,e)把在区间(b,e)中定义的元素重新排列成非递减序列,在<algotithm>中定义
    8. max(e1,e2)返回e1,e2中的较大值,在<algotithm>中定义
  • 输入一组数,返回中值和平均值。

#include <algorithm>using namespace std;int main() {    cout << "Please enter the num(push ctrl+z to end):";    vector<double> num;    double x,sum=0;    //输入数字    while (cin >> x) {        num.push_back(x);        sum += x;    }    int size = num.size();    //对数字排序并计算中值    sort(num.begin(), num.end());    double mid = (size % 2 == 0) ? (num[size / 2 - 1] + num[size / 2 ]) / 2 : num[(size - 1) / 2];    double avg = sum / size;    cout << "mid=" << mid << endl << "avg=" << avg << endl;    system("pause");    return 0;}
0 0
原创粉丝点击