1.vector的初始化 使用vector myint{1, 2, 3, 4, 5}, 以及在vector中取数据, 使用.at或者[]

int main1()
{
    vector<int> myint{1, 2, 3, 4, 5};

    for(int i = 10; i < 20; i++)
    {
        myint.push_back(i);
    }
//    cout << myint.front() << endl; //存储数据
//    cout << myint.back() << endl;
  //  for(auto i:myint)
//    {
   //     cout << i << endl;
    //}
    //myint.resize(5); //动态调整大小
//    myint.resize(6, 90); //vector只有6个数据, 缓冲有90
//    for(auto ib=myint.begin(), ie = myint.end(); ie != ib; ib++)
//    {
//        cout << *ib << endl;
//    }

//    for(auto rb=myint.rbegin(), re = myint.end(); re != rb; rb++)
    //{
//        cout << *rb << endl;
    //}
//    for(int i = 0; i < myint.size();++i)
//    {
//        cout << myint[i] <<" " << myint.at(i) << endl;
//    }
}

2.vector中插入数据, 使用myint.insert(it, 400) 根据位置插入数据, 以及插入数组

int main2()
{
    //插入
    vector<int> myintX{11, 12, 13, 14, 15};
    vector<int> myint{1, 2, 3, 4, 5};
    //myint.assign(7, 100); //重新初始化
    auto it = myint.begin() + 3;
    int a[5] = {21, 22, 23, 24, 25};
//    it = myint.insert(it, 400); //根据位置插入
//    cout << *it << endl;
//    it = myint.insert(it, a, a+5); //插入一个数组
    it = myint.insert(it, myintX.begin(), myintX.end()); //批量插入
      for(auto i:myint)
    {
         cout << i << endl;
    }
      return 0;
}

vector批量删除数据,使用.erase进行数据删除

int main3()
{
    vector<int> myint{1, 2, 3, 4, 5};
    auto it = myint.begin() + 3;
    //myint.erase(it);
    myint.erase(myint.begin(), myint.begin() + 3); //批量删除, 不包含最后的位置
    for(auto i:myint)
    {
        cout << i << endl;
    }
    return 0;
}

vector数据交换, 使用.swap进行数据交换


int main4() {
    vector<int> myint{1, 2, 3, 4, 5};
    vector<int> myint2{3, 32, 33, 34, 35};
    myint.swap(myint2);
    for (auto i:myint) {
        cout << i << endl;
    }
    for (auto i:myint2) {
        cout << i << endl;
    }
}

vector获取分配器分配内存

int main7() {
    vector<int> myint1;
    int *p = myint1.get_allocator().allocate(5); //获取分配器分配内存
    cout << myint1.size() << endl;
    for (int i = 0; i < 5; i++) {
        cout << (p[i] = i) << myint1[i] << endl;
    }
    myint1.get_allocator().deallocate(p, 5); //释放内存

    cin.get(); //自动管理内存
}

vector构造二维数组, 使用vector<vector>

int main()
{
    vector<int> myint1{1, 2, 3, 4, 5};
    vector<int> myint2{1, 2, 3, 4, 5, 6, 7};
    vector<int> myint3{1, 2, 3};
    vector<vector<int>>myallint{myint1, myint2, myint3}; //构造vector的二维数组
    for(auto i:myallint)
    {
        for(auto j:i)
        {
            cout << j << " ";
        }
        cout << "\n";
    }
    cin.get();
}

标签: C++, int, cout, vector, 分配内存, auto, 插入, myint

相关文章推荐

添加新评论,含*的栏目为必填