学习vector,记录一下

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
/*int main()
{
    string s = "qwertyuiop";//使用string定义字符串
    int a[] = { 5,3,3,2,1 };
    sort(a, a + 5);//对a排序
    cout << s << endl;
    cout << *(a+3) << endl;
    return 0;
}*/
int main()
{
    vector<int> v1;//定义空vector
    vector<int> v2(4);//初始为0的4位vector
    vector<int> v3(4,6);//初始为6的4位vector
    vector<int> v4 = { 1,2,3,4,5 };//初始位1,2,3,4,5的vector 
    /*-------------------------------*/
    cout << "-----vector的定义方式-----:" << endl;
    for (auto x : v1)cout << x;
    cout << endl;
    for (auto x : v2)cout << x;
    cout << endl;
    for (auto x : v3)cout << x;
    cout << endl;
    for (auto x : v4)cout << x;
    cout << endl;

    /*-------------------------------*/

    cout << "-----获取元素-----:" << endl;
    cout << v4[0] << ' ' << v4.at(1);//使用中括号或at来获取vector中的元素
    cout << endl;

    /*-------------------------------*/

    cout << "-----改变vector-----:" << endl;
    v4.push_back(6);//使用push_back在vector最后面增加元素
    for (auto x : v4)cout << x;
    cout << endl;

    v4.resize(10, 7);//使用resize重置大小;或填充数字(若要填充0,可以写成v4.resize(n);
    for (auto x : v4)cout << x;
    cout << endl;
    v4.resize(7);
    for (auto x : v4)cout << x;    
    cout << endl;

    v4.erase(v4.begin());
    v4.erase(--v4.end());//使用erase进行vector中元素的删除(erase复杂度为O(n))
    for (auto x : v4)cout << x;
    cout << endl;

    cout << v4.front() << endl << v4.back() << endl;//获取第一个和最后一个元素(也可以使用v[n]来获取)
    cout << *v4.begin() << endl;//同样获取第一个元素
    cout << v4[v4.size() - 2] << endl;//获取倒数第n个元素
    cout << *--v4.end() << endl;//获取最后一个元素

    /*-------------------------------*/

    cout << "-----排序-----:" << endl;

    vector<int> v5 = { 5,2,6,1,-1 };
    sort(v5.begin(), v5.end());//从小到大排序(末尾忽略了less<int>(),同下方greater<int>())
    for (auto x : v5)cout << x << ' ';
    cout << endl;
    sort(v5.begin(), v5.end(), greater<int>());//从大到小排序:使用greater<int>()
    for (auto x : v5)cout << x << ' ';
    cout << endl;

    /*-------------------------------*/

    cout << "-----循环-----:" << endl;

    for (int i = 0; i < v4.size(); i++) cout << v4[i];//for循环
    cout << endl;
    for (vector<int>::iterator it = v4.begin(); it != v4.end();it++) cout << *it;//迭代器循环
    cout << endl;
    for (auto it = v4.begin(); it != v4.end(); it++) cout << *it;//简化迭代器循环(有时不支持)
    cout << endl;
    for (auto x : v4)cout << x;//c++11新特性
    cout << endl;
}

5月15日