Vector-Sort

  • + 0 comments

    Instead of using a for loop paired with push_back() (which can result in allocations that could otherwise be avoided), use the explicit constructor, std::vector<T>(int) (requiring direct initialisation via a parenthesised list) which constructs a std::vector of a given size:

    int main()
    {
        int size {};
        std::cin >> size;
        
        // Constructs a 'std::vector' of given size
        std::vector<int> v (size);
        
        // Loops through the vector by reference
        // setting its elements to inputted values
        for(auto& i : v)
            std::cin >> i;
            
        std::sort(v.begin(), v.end());
        
        for(auto i : v)
            std::cout << i << ' ';
        
        return 0;
    }