• 26 函数形参值回传问题——C++解决多个return的一般方法


    0 引言

    在使用数组和vector作为函数的参数进行参数传递并希望得到值的回传时,由于不知道怎么写数组函数形参的引用形式,一直采用vector的引用形式。但是,刚刚测试了一下,发现数组作为参数本身就是指针,根本不需要采用引用形式把值回传啊,把测试结果写下来。

    1 关于数组作为函数参数的值传递问题——数组和容器的对比

      数组直接作为形参进行传递,容器(以vector为例)以引用形式作为形参

      1. 函数代码

    void arrayTest(double myarray[3]){
        for(int i=0; i<3; ++i){
            myarray[i] = i+1;
        }
    }
    
    void vectorTest(vector<int>& myVector){
        for(int i=0; i<3; ++i){
            myVector[i] = i+1;
        }
    }

      2. 测试代码

    void arrayAndVectorTest(){
        double myarray[3] = {0,0,0};
        arrayTest(myarray);
        cout << "array test" <<endl;
        for(int i=0; i<3;i++){
            cout << "" << i << "个数 = " << myarray[i] << endl;
        }    
        vector<int> myVector{0,0,0};
        vectorTest(myVector);
        cout << "vector test" <<endl;
        for(auto it = myVector.begin(); it != myVector.end(); ++ it)
            cout << "" << it -myVector.begin() + 1  << "个数 = " << *it << endl;
    }

      3. 测试结果如下

       

      两种方法均实现了值的回传.

      4. 数组直接作为形参进行传递,容器(以vector为例)以引用形式作为形参  

    void vectorTest(vector<int> myVector){
        for(int i=0; i<3; ++i){
            myVector[i] = i+1;
        }
    }

       

      此时,数组实现了值回传,但是容器没有实现值回传。

  • 相关阅读:
    Python常用函数
    Mock测试&Postman mockserver详细教程
    openpyxl模块
    adb 'grep' 不是内部或外部命令,也不是可运行的程序或批处理文件
    Appium-Python-Windows环境搭建笔记
    调用类方法时报错:missing 1 required positional argument: 'self'
    RE正则表达式-元字符
    微分方程
    操作系统学习记录
    Mybatis基础配置
  • 原文地址:https://www.cnblogs.com/ghjnwk/p/10152027.html
Copyright © 2020-2023  润新知