Correct way to display array

3

Which way is the most recommended to show an array in a function?

typedef int TVector[10];
  • with const :

    void MostrarArray(const TVector &v){}
                      ^^^^^^^^^^^^^^^^
    
  • directly:

    void MostrarArray(TVector v){}
                      ^^^^^^^^^
    
  • Code

    int main() {
    
        TVector v;
    
        MostrarArray(v);
    
        return 0;
    }
    
        
    asked by Akarin 16.08.2016 в 02:01
    source

    2 answers

    3

    If the goal of mostrarArray is just to show your data on the screen, the correct option is constant reference (to avoid copies) (it is not expected to be modified).

    The TVector you have used limits the use to static arrays of 10 elements, but if you need a mostrarArray function for static arrays of known size at compile time you could use this alternative:

    template <std::size_t TAMANYO>
    void MostrarArray(const int (&v)[TAMANYO]){}
    
    int main()
    {
        TVector v{};
        int x[]{1,2,3,4,5,6,7,8,9,0};
        int y[]{1,2,3,4,5};
    
        MostrarArray(v);
        MostrarArray(x);
        MostrarArray(y); // esto seria error con la version que recibe const TVector &
    
        return 0;
    }
    
        
    answered by 16.08.2016 / 11:53
    source
    1

    It seems to me that the C ++ 17 standard is coming out, and already in full use of C ++ 14 and C ++ 11, frankly, it is not convenient to devote more time and energy to the usual forms more than 18 years ago. So I would say that one of the preferred ways in C ++ is to use std :: vector as the default container, unless it is decided by another (like std :: list, std :: deque, std :: array or others ).

    Using a std :: vector, the simplest and most usual way I think it is

    #include <iostream>
    #include <vector>
    
    void mostrarArray(const std::vector<int>& a)
    {
        for(const auto& i : a)
            std::cout << i << ' ';
        std::cout << '\n';
    }
    
    int main()
    {
        std::vector<int> a{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        mostrarArray(a);
    }
    
        
    answered by 16.08.2016 в 04:16