• 003.关于数组的操作 [growing]


    1.获取数组的长度

    #include<iostream>
    using namespace std;
    
    template<class T>
    int length(T& arr)
    {
        //cout << sizeof(arr[0]) << endl;
        //cout << sizeof(arr) << endl;
        return sizeof(arr) / sizeof(arr[0]);//总长除以单个元素长度
    }
    
    int main()
    {
        int arr[] = { 1,5,9,10,9,2 };
        // 方法一
        cout << "数组的长度为:" << length(arr) << endl;
        // 方法二
        //cout << end(arr) << endl;
        //cout << begin(arr) << endl;
        cout << "数组的长度为:" << end(arr)-begin(arr) << endl;return 0;
    }

    2.传递数组参数

    /*打印一个字符串中所有字母的全排列(假设不含重复字母))*/
    
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    //void printAllArr(char *str,int i){}
    void printAllArr(char str[],int i) {
        int n = sizeof(str)/sizeof(str[0])-1;//获取数组长度
        //cout << n << endl;
    
        if (i == n-1) {
            for(int w  = 0; w < n;++w){
                cout << str[w];
            }
            cout << endl;
            return;
        }
        else {
            for (int j = i; j <n; ++j) {
                swap(str[i], str[j]);
                printAllArr(str, i + 1);
                swap(str[i], str[j]);
            }
        }
        
    }
    
    void main() {
        string test = "abc";
        char  v[4];
        strncpy_s(v, test.c_str(), test.length() + 1);//必须加1,还占一个位置
        printAllArr(v, 0);
    }

    参考资料:

    1.C++获取数组的长度

  • 相关阅读:
    python_day_5:20180720
    python_day_4:20180719
    2018悦读
    2018生活
    心理画
    js 策略模式
    js 单例模式
    js 模板方法模式
    C语言-数据类型
    js 观察者模式
  • 原文地址:https://www.cnblogs.com/paulprayer/p/10004059.html
Copyright © 2020-2023  润新知