zoukankan      html  css  js  c++  java
  • 数据结构动态数组

    数组具有固定的容量,我们需要在初始化时指定数组的大小。有时它会非常不方便并可能造成浪费。

    因此,大多数编程语言都提供内置的动态数组它仍然是一个随机存取的列表数据结构,大小是可变的例如,在 C++ 中的 vector,以及在 Java 中的 ArrayList

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main() {
        // 1. initialize
        vector<int> v0;
        vector<int> v1(5, 0);
        // 2. make a copy
        vector<int> v2(v1.begin(), v1.end());
        vector<int> v3(v2);
        // 2. cast an array to a vector
        int a[5] = { 0, 1, 2, 3, 4 };
        vector<int> v4(a, *(&a + 1));
        // 3. get length
        cout << "The size of v4 is: " << v4.size() << endl;
        // 4. access element
        cout << "The first element in v4 is: " << v4[0] << endl;
        // 5. iterate the vector
        cout << "[Version 1] The contents of v4 are:";
        for (int i = 0; i < v4.size(); ++i) {
            cout << " " << v4[i];
        }
        cout << endl;
        cout << "[Version 2] The contents of v4 are:";
        for (int& item : v4) {
            cout << " " << item;
        }
        cout << endl;
        cout << "[Version 3] The contents of v4 are:";
        for (auto item = v4.begin(); item != v4.end(); ++item) {
            cout << " " << *item;
        }
        cout << endl;
        // 6. modify element
        v4[0] = 5;
        // 7. sort
        sort(v4.begin(), v4.end());
        // 8. add new element at the end of the vector
        v4.push_back(-1);
        // 9. delete the last element
        v4.pop_back();
        system("pause");
    }

     这里学习一下 auto关键字:auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型

    ps:auto 变量必须在定义时初始化,这类似于const关键字。

  • 相关阅读:
    myeclipse python下配置文档说明_转载
    Python快速教程博客园地址
    Mysql_存储功能
    Java_链表实现
    浅谈JAVA集合框架(转载)_常用的Vector和HashMap
    Java_Vector类的使用,以及Stack继承Vector,推出的栈的特性
    JavaWeb_数据传输_原
    HTML <input> 标签的 type 属性
    Java_Web_request.setAttribute("result",username);
    秦柯视频与文档资料-全集
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10783170.html
Copyright © 2011-2022 走看看