Pass a dynamic array of objects to function

前端 未结 3 2019
说谎
说谎 2021-01-06 16:58

I am in the process of learning c++. So i know a method by which you send something to function and then work as if it was call by value but actually it is call by reference

相关标签:
3条回答
  • 2021-01-06 17:37

    Arrays are by default converted to pointers, which are then passed as reference. So, there is no provision for explicitly passing arrays by reference. That is,

    void list_cities(int number, City &p[])
    

    is not p[] being passed as reference, but makes p[] an array of references.

    Code:

    void list_cities(int number, City p[])
    {
        for(int i=0; i<number; i++)
        {
            cout<<p[i].get_name()<<endl;
        }
    }
    
    int main()
    {
        City *p = new City[number];
        list_cities(number,p);
        delete[] p;
    }
    
    0 讨论(0)
  • 2021-01-06 17:40

    Confusingly, a function parameter that looks like an array City p[] is actually a pointer, equivalent to City * p. So you can just pass a pointer to your dynamic array:

    list_cities(number, p);
    

    That said, prefer friendly types like std::vector<City> so you don't have to juggle pointers and carefully avoid memory leaks and worse.

    0 讨论(0)
  • 2021-01-06 17:49

    Using std::vector you can also do the following:

    void list_cities(std::vector<City> &cities)
    {
        for (size_t iCity = 0; iCity < cities.size(); iCity++){
            cout << cities[iCity].get_name() << endl;
        }
    }
    
    std::vector<City> cities;
    // fill list here
    list_cities(cities);
    
    0 讨论(0)
提交回复
热议问题