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++获取数组的长度

原文地址:https://www.cnblogs.com/paulprayer/p/10004059.html