Arrays Introduction

  • + 7 comments

    We don't want to use C-style array in C++. We use STL containers instead, which have a lot of advantages such as being compatible with STL algorithms, or providing useful member functions such as 'std::vector::size()' (to get the size of the array :D). In this case, we can use 'std::vector', which is a dynamic array. Here's the solution in true C++:

    #include <vector>
    #include <iostream>
    #include <iterator>
    
    int main()
    {
        std::size_t size{}; // Here we use 'std::size_t' instead of 'int'
                            // because an array size cannot be negative
        std::cin >> size;
        std::vector<int> vect(size);
        for (std::size_t i{}; i < size; ++i)
        	std::cin >> vect[i];
    
        // One of the many advantages to use C++ STL containers:
        // we can use reverse iterators
        for (auto rit = vect.rbegin(); rit != vect.rend(); ++rit)
            std::cout << *rit << ' ';
        std::cout << std::endl;
        return 0;
    }